blob: e21a9c46ee870ca88809b238dad2b9a9ad99adea [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>
William Roberts8a5b9ca2016-04-08 12:13:17 -070024#include <pwd.h>
Pierre Zurekead88fc2010-10-17 22:39:37 +020025#include <stdbool.h>
Mark Salyzyna04464a2014-04-30 08:50:53 -070026#include <stdint.h>
27#include <stdio.h>
28#include <stdlib.h>
29#include <string.h>
Jeff Brown44193d92015-04-28 12:47:02 -070030#include <inttypes.h>
Pierre Zurekead88fc2010-10-17 22:39:37 +020031#include <sys/param.h>
William Roberts8a5b9ca2016-04-08 12:13:17 -070032#include <sys/types.h>
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -070033
Mark Salyzyn4cbed022015-08-31 15:53:41 -070034#include <cutils/list.h>
Colin Cross9227bd32013-07-23 16:59:20 -070035#include <log/logd.h>
36#include <log/logprint.h>
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -070037
Mark Salyzyn018a96d2016-03-01 13:45:42 -080038#include "log_portability.h"
Mark Salyzynbe1d3c22016-03-10 08:25:33 -080039
Mark Salyzyn4cbed022015-08-31 15:53:41 -070040#define MS_PER_NSEC 1000000
41#define US_PER_NSEC 1000
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 */
Mark Salyzynbe1d3c22016-03-10 08:25:33 -0800188LIBLOG_ABI_PUBLIC int android_log_shouldPrintLine (
189 AndroidLogFormat *p_format,
190 const char *tag,
191 android_LogPriority pri)
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -0700192{
193 return pri >= filterPriForTag(p_format, tag);
194}
195
Mark Salyzynbe1d3c22016-03-10 08:25:33 -0800196LIBLOG_ABI_PUBLIC AndroidLogFormat *android_log_format_new()
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -0700197{
198 AndroidLogFormat *p_ret;
199
200 p_ret = calloc(1, sizeof(AndroidLogFormat));
201
202 p_ret->global_pri = ANDROID_LOG_VERBOSE;
203 p_ret->format = FORMAT_BRIEF;
Pierre Zurekead88fc2010-10-17 22:39:37 +0200204 p_ret->colored_output = false;
Mark Salyzyne1f20042015-05-06 08:40:40 -0700205 p_ret->usec_time_output = false;
Mark Salyzynb932b2f2015-05-15 09:01:58 -0700206 p_ret->printable_output = false;
Mark Salyzynf28f6a92015-08-31 08:01:33 -0700207 p_ret->year_output = false;
208 p_ret->zone_output = false;
Mark Salyzyn4cbed022015-08-31 15:53:41 -0700209 p_ret->epoch_output = false;
Mark Salyzynba7a9a02015-12-01 15:57:25 -0800210 p_ret->monotonic_output = android_log_clockid() == CLOCK_MONOTONIC;
Mark Salyzyn90e7af32015-12-07 16:52:42 -0800211 p_ret->uid_output = false;
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -0700212
213 return p_ret;
214}
215
Mark Salyzyn4cbed022015-08-31 15:53:41 -0700216static list_declare(convertHead);
217
Mark Salyzynbe1d3c22016-03-10 08:25:33 -0800218LIBLOG_ABI_PUBLIC void android_log_format_free(AndroidLogFormat *p_format)
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -0700219{
220 FilterInfo *p_info, *p_info_old;
221
222 p_info = p_format->filters;
223
224 while (p_info != NULL) {
225 p_info_old = p_info;
226 p_info = p_info->p_next;
227
228 free(p_info_old);
229 }
230
231 free(p_format);
Mark Salyzyn4cbed022015-08-31 15:53:41 -0700232
233 /* Free conversion resource, can always be reconstructed */
234 while (!list_empty(&convertHead)) {
235 struct listnode *node = list_head(&convertHead);
236 list_remove(node);
237 free(node);
238 }
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -0700239}
240
Mark Salyzynbe1d3c22016-03-10 08:25:33 -0800241LIBLOG_ABI_PUBLIC int android_log_setPrintFormat(
242 AndroidLogFormat *p_format,
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -0700243 AndroidLogPrintFormat format)
244{
Mark Salyzynb932b2f2015-05-15 09:01:58 -0700245 switch (format) {
246 case FORMAT_MODIFIER_COLOR:
Pierre Zurekead88fc2010-10-17 22:39:37 +0200247 p_format->colored_output = true;
Mark Salyzyne1f20042015-05-06 08:40:40 -0700248 return 0;
Mark Salyzynb932b2f2015-05-15 09:01:58 -0700249 case FORMAT_MODIFIER_TIME_USEC:
Mark Salyzyne1f20042015-05-06 08:40:40 -0700250 p_format->usec_time_output = true;
251 return 0;
Mark Salyzynb932b2f2015-05-15 09:01:58 -0700252 case FORMAT_MODIFIER_PRINTABLE:
253 p_format->printable_output = true;
254 return 0;
Mark Salyzynf28f6a92015-08-31 08:01:33 -0700255 case FORMAT_MODIFIER_YEAR:
256 p_format->year_output = true;
257 return 0;
258 case FORMAT_MODIFIER_ZONE:
259 p_format->zone_output = !p_format->zone_output;
260 return 0;
Mark Salyzyn4cbed022015-08-31 15:53:41 -0700261 case FORMAT_MODIFIER_EPOCH:
262 p_format->epoch_output = true;
263 return 0;
264 case FORMAT_MODIFIER_MONOTONIC:
265 p_format->monotonic_output = true;
266 return 0;
Mark Salyzyn90e7af32015-12-07 16:52:42 -0800267 case FORMAT_MODIFIER_UID:
268 p_format->uid_output = true;
269 return 0;
Mark Salyzynb932b2f2015-05-15 09:01:58 -0700270 default:
271 break;
Mark Salyzyne1f20042015-05-06 08:40:40 -0700272 }
273 p_format->format = format;
274 return 1;
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -0700275}
276
Mark Salyzynf28f6a92015-08-31 08:01:33 -0700277static const char tz[] = "TZ";
278static const char utc[] = "UTC";
279
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -0700280/**
281 * Returns FORMAT_OFF on invalid string
282 */
Mark Salyzynbe1d3c22016-03-10 08:25:33 -0800283LIBLOG_ABI_PUBLIC AndroidLogPrintFormat android_log_formatFromString(
284 const char * formatString)
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -0700285{
286 static AndroidLogPrintFormat format;
287
288 if (strcmp(formatString, "brief") == 0) format = FORMAT_BRIEF;
289 else if (strcmp(formatString, "process") == 0) format = FORMAT_PROCESS;
290 else if (strcmp(formatString, "tag") == 0) format = FORMAT_TAG;
291 else if (strcmp(formatString, "thread") == 0) format = FORMAT_THREAD;
292 else if (strcmp(formatString, "raw") == 0) format = FORMAT_RAW;
293 else if (strcmp(formatString, "time") == 0) format = FORMAT_TIME;
294 else if (strcmp(formatString, "threadtime") == 0) format = FORMAT_THREADTIME;
295 else if (strcmp(formatString, "long") == 0) format = FORMAT_LONG;
Mark Salyzyne1f20042015-05-06 08:40:40 -0700296 else if (strcmp(formatString, "color") == 0) format = FORMAT_MODIFIER_COLOR;
297 else if (strcmp(formatString, "usec") == 0) format = FORMAT_MODIFIER_TIME_USEC;
Mark Salyzynb932b2f2015-05-15 09:01:58 -0700298 else if (strcmp(formatString, "printable") == 0) format = FORMAT_MODIFIER_PRINTABLE;
Mark Salyzynf28f6a92015-08-31 08:01:33 -0700299 else if (strcmp(formatString, "year") == 0) format = FORMAT_MODIFIER_YEAR;
300 else if (strcmp(formatString, "zone") == 0) format = FORMAT_MODIFIER_ZONE;
Mark Salyzyn4cbed022015-08-31 15:53:41 -0700301 else if (strcmp(formatString, "epoch") == 0) format = FORMAT_MODIFIER_EPOCH;
302 else if (strcmp(formatString, "monotonic") == 0) format = FORMAT_MODIFIER_MONOTONIC;
Mark Salyzyn90e7af32015-12-07 16:52:42 -0800303 else if (strcmp(formatString, "uid") == 0) format = FORMAT_MODIFIER_UID;
Mark Salyzynf28f6a92015-08-31 08:01:33 -0700304 else {
305 extern char *tzname[2];
306 static const char gmt[] = "GMT";
307 char *cp = getenv(tz);
308 if (cp) {
309 cp = strdup(cp);
310 }
311 setenv(tz, formatString, 1);
312 /*
313 * Run tzset here to determine if the timezone is legitimate. If the
314 * zone is GMT, check if that is what was asked for, if not then
315 * did not match any on the system; report an error to caller.
316 */
317 tzset();
318 if (!tzname[0]
319 || ((!strcmp(tzname[0], utc)
320 || !strcmp(tzname[0], gmt)) /* error? */
321 && strcasecmp(formatString, utc)
322 && strcasecmp(formatString, gmt))) { /* ok */
323 if (cp) {
324 setenv(tz, cp, 1);
325 } else {
326 unsetenv(tz);
327 }
328 tzset();
329 format = FORMAT_OFF;
330 } else {
331 format = FORMAT_MODIFIER_ZONE;
332 }
333 free(cp);
334 }
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -0700335
336 return format;
337}
338
339/**
340 * filterExpression: a single filter expression
341 * eg "AT:d"
342 *
343 * returns 0 on success and -1 on invalid expression
344 *
345 * Assumes single threaded execution
346 */
347
Mark Salyzynbe1d3c22016-03-10 08:25:33 -0800348LIBLOG_ABI_PUBLIC int android_log_addFilterRule(
349 AndroidLogFormat *p_format,
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -0700350 const char *filterExpression)
351{
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -0700352 size_t tagNameLength;
353 android_LogPriority pri = ANDROID_LOG_DEFAULT;
354
355 tagNameLength = strcspn(filterExpression, ":");
356
357 if (tagNameLength == 0) {
358 goto error;
359 }
360
361 if(filterExpression[tagNameLength] == ':') {
362 pri = filterCharToPri(filterExpression[tagNameLength+1]);
363
364 if (pri == ANDROID_LOG_UNKNOWN) {
365 goto error;
366 }
367 }
368
369 if(0 == strncmp("*", filterExpression, tagNameLength)) {
Mark Salyzynb932b2f2015-05-15 09:01:58 -0700370 /*
371 * This filter expression refers to the global filter
372 * The default level for this is DEBUG if the priority
373 * is unspecified
374 */
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -0700375 if (pri == ANDROID_LOG_DEFAULT) {
376 pri = ANDROID_LOG_DEBUG;
377 }
378
379 p_format->global_pri = pri;
380 } else {
Mark Salyzynb932b2f2015-05-15 09:01:58 -0700381 /*
382 * for filter expressions that don't refer to the global
383 * filter, the default is verbose if the priority is unspecified
384 */
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -0700385 if (pri == ANDROID_LOG_DEFAULT) {
386 pri = ANDROID_LOG_VERBOSE;
387 }
388
389 char *tagName;
390
Mark Salyzynb932b2f2015-05-15 09:01:58 -0700391/*
392 * Presently HAVE_STRNDUP is never defined, so the second case is always taken
393 * Darwin doesn't have strnup, everything else does
394 */
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -0700395#ifdef HAVE_STRNDUP
396 tagName = strndup(filterExpression, tagNameLength);
397#else
Mark Salyzynb932b2f2015-05-15 09:01:58 -0700398 /* a few extra bytes copied... */
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -0700399 tagName = strdup(filterExpression);
400 tagName[tagNameLength] = '\0';
401#endif /*HAVE_STRNDUP*/
402
403 FilterInfo *p_fi = filterinfo_new(tagName, pri);
404 free(tagName);
405
406 p_fi->p_next = p_format->filters;
407 p_format->filters = p_fi;
408 }
409
410 return 0;
411error:
412 return -1;
413}
414
415
416/**
417 * filterString: a comma/whitespace-separated set of filter expressions
418 *
419 * eg "AT:d *:i"
420 *
421 * returns 0 on success and -1 on invalid expression
422 *
423 * Assumes single threaded execution
424 *
425 */
426
Mark Salyzynbe1d3c22016-03-10 08:25:33 -0800427LIBLOG_ABI_PUBLIC int android_log_addFilterString(
428 AndroidLogFormat *p_format,
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -0700429 const char *filterString)
430{
431 char *filterStringCopy = strdup (filterString);
432 char *p_cur = filterStringCopy;
433 char *p_ret;
434 int err;
435
Mark Salyzynb932b2f2015-05-15 09:01:58 -0700436 /* Yes, I'm using strsep */
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -0700437 while (NULL != (p_ret = strsep(&p_cur, " \t,"))) {
Mark Salyzynb932b2f2015-05-15 09:01:58 -0700438 /* ignore whitespace-only entries */
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -0700439 if(p_ret[0] != '\0') {
440 err = android_log_addFilterRule(p_format, p_ret);
441
442 if (err < 0) {
443 goto error;
444 }
445 }
446 }
447
448 free (filterStringCopy);
449 return 0;
450error:
451 free (filterStringCopy);
452 return -1;
453}
454
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -0700455/**
456 * Splits a wire-format buffer into an AndroidLogEntry
457 * entry allocated by caller. Pointers will point directly into buf
458 *
459 * Returns 0 on success and -1 on invalid wire format (entry will be
460 * in unspecified state)
461 */
Mark Salyzynbe1d3c22016-03-10 08:25:33 -0800462LIBLOG_ABI_PUBLIC int android_log_processLogBuffer(
463 struct logger_entry *buf,
464 AndroidLogEntry *entry)
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -0700465{
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -0700466 entry->tv_sec = buf->sec;
467 entry->tv_nsec = buf->nsec;
Mark Salyzyn90e7af32015-12-07 16:52:42 -0800468 entry->uid = -1;
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -0700469 entry->pid = buf->pid;
470 entry->tid = buf->tid;
Kenny Root4bf3c022011-09-30 17:10:14 -0700471
472 /*
473 * format: <priority:1><tag:N>\0<message:N>\0
474 *
475 * tag str
Nick Kraleviche1ede152011-10-18 15:23:33 -0700476 * starts at buf->msg+1
Kenny Root4bf3c022011-09-30 17:10:14 -0700477 * msg
Nick Kraleviche1ede152011-10-18 15:23:33 -0700478 * starts at buf->msg+1+len(tag)+1
Jeff Sharkeya820a0e2011-10-26 18:40:39 -0700479 *
480 * The message may have been truncated by the kernel log driver.
481 * When that happens, we must null-terminate the message ourselves.
Kenny Root4bf3c022011-09-30 17:10:14 -0700482 */
Nick Kraleviche1ede152011-10-18 15:23:33 -0700483 if (buf->len < 3) {
Mark Salyzynb932b2f2015-05-15 09:01:58 -0700484 /*
485 * An well-formed entry must consist of at least a priority
486 * and two null characters
487 */
Nick Kraleviche1ede152011-10-18 15:23:33 -0700488 fprintf(stderr, "+++ LOG: entry too small\n");
Kenny Root4bf3c022011-09-30 17:10:14 -0700489 return -1;
490 }
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -0700491
Jeff Sharkeya820a0e2011-10-26 18:40:39 -0700492 int msgStart = -1;
493 int msgEnd = -1;
494
Nick Kraleviche1ede152011-10-18 15:23:33 -0700495 int i;
Mark Salyzyn40b21552013-12-18 12:59:01 -0800496 char *msg = buf->msg;
497 struct logger_entry_v2 *buf2 = (struct logger_entry_v2 *)buf;
498 if (buf2->hdr_size) {
Mark Salyzyn305374c2016-08-18 14:59:41 -0700499 if ((buf2->hdr_size < sizeof(((struct log_msg *)NULL)->entry_v1)) ||
500 (buf2->hdr_size > sizeof(((struct log_msg *)NULL)->entry))) {
501 fprintf(stderr, "+++ LOG: entry illegal hdr_size\n");
502 return -1;
503 }
Mark Salyzyn40b21552013-12-18 12:59:01 -0800504 msg = ((char *)buf2) + buf2->hdr_size;
Mark Salyzyn90e7af32015-12-07 16:52:42 -0800505 if (buf2->hdr_size >= sizeof(struct logger_entry_v4)) {
506 entry->uid = ((struct logger_entry_v4 *)buf)->uid;
507 }
Mark Salyzyn40b21552013-12-18 12:59:01 -0800508 }
Nick Kraleviche1ede152011-10-18 15:23:33 -0700509 for (i = 1; i < buf->len; i++) {
Mark Salyzyn40b21552013-12-18 12:59:01 -0800510 if (msg[i] == '\0') {
Jeff Sharkeya820a0e2011-10-26 18:40:39 -0700511 if (msgStart == -1) {
512 msgStart = i + 1;
513 } else {
514 msgEnd = i;
515 break;
516 }
Nick Kraleviche1ede152011-10-18 15:23:33 -0700517 }
518 }
Jeff Sharkeya820a0e2011-10-26 18:40:39 -0700519
520 if (msgStart == -1) {
Mark Salyzyn083c5342016-03-21 09:45:34 -0700521 /* +++ LOG: malformed log message, DYB */
522 for (i = 1; i < buf->len; i++) {
523 /* odd characters in tag? */
524 if ((msg[i] <= ' ') || (msg[i] == ':') || (msg[i] >= 0x7f)) {
525 msg[i] = '\0';
526 msgStart = i + 1;
527 break;
528 }
529 }
530 if (msgStart == -1) {
531 msgStart = buf->len - 1; /* All tag, no message, print truncates */
532 }
Nick Kralevich63f4a842011-10-17 10:45:03 -0700533 }
Jeff Sharkeya820a0e2011-10-26 18:40:39 -0700534 if (msgEnd == -1) {
Mark Salyzynb932b2f2015-05-15 09:01:58 -0700535 /* incoming message not null-terminated; force it */
Mark Salyzynd7bcf402015-12-04 09:24:15 -0800536 msgEnd = buf->len - 1; /* may result in msgEnd < msgStart */
Mark Salyzyn40b21552013-12-18 12:59:01 -0800537 msg[msgEnd] = '\0';
Jeff Sharkeya820a0e2011-10-26 18:40:39 -0700538 }
539
Mark Salyzyn40b21552013-12-18 12:59:01 -0800540 entry->priority = msg[0];
541 entry->tag = msg + 1;
542 entry->message = msg + msgStart;
Mark Salyzynd7bcf402015-12-04 09:24:15 -0800543 entry->messageLen = (msgEnd < msgStart) ? 0 : (msgEnd - msgStart);
Nick Kralevich63f4a842011-10-17 10:45:03 -0700544
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -0700545 return 0;
546}
547
548/*
Mark Salyzyn8470dad2015-03-06 20:42:57 +0000549 * Extract a 4-byte value from a byte stream.
550 */
551static inline uint32_t get4LE(const uint8_t* src)
552{
553 return src[0] | (src[1] << 8) | (src[2] << 16) | (src[3] << 24);
554}
555
556/*
557 * Extract an 8-byte value from a byte stream.
558 */
559static inline uint64_t get8LE(const uint8_t* src)
560{
561 uint32_t low, high;
562
563 low = src[0] | (src[1] << 8) | (src[2] << 16) | (src[3] << 24);
564 high = src[4] | (src[5] << 8) | (src[6] << 16) | (src[7] << 24);
Jeff Brown44193d92015-04-28 12:47:02 -0700565 return ((uint64_t) high << 32) | (uint64_t) low;
Mark Salyzyn8470dad2015-03-06 20:42:57 +0000566}
567
568
569/*
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -0700570 * Recursively convert binary log data to printable form.
571 *
572 * This needs to be recursive because you can have lists of lists.
573 *
574 * If we run out of room, we stop processing immediately. It's important
575 * for us to check for space on every output element to avoid producing
576 * garbled output.
577 *
578 * Returns 0 on success, 1 on buffer full, -1 on failure.
579 */
580static int android_log_printBinaryEvent(const unsigned char** pEventData,
581 size_t* pEventDataLen, char** pOutBuf, size_t* pOutBufLen)
582{
583 const unsigned char* eventData = *pEventData;
584 size_t eventDataLen = *pEventDataLen;
585 char* outBuf = *pOutBuf;
586 size_t outBufLen = *pOutBufLen;
587 unsigned char type;
588 size_t outCount;
589 int result = 0;
590
591 if (eventDataLen < 1)
592 return -1;
593 type = *eventData++;
594 eventDataLen--;
595
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -0700596 switch (type) {
597 case EVENT_TYPE_INT:
598 /* 32-bit signed int */
599 {
600 int ival;
601
602 if (eventDataLen < 4)
603 return -1;
Mark Salyzyn8470dad2015-03-06 20:42:57 +0000604 ival = get4LE(eventData);
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -0700605 eventData += 4;
606 eventDataLen -= 4;
607
608 outCount = snprintf(outBuf, outBufLen, "%d", ival);
609 if (outCount < outBufLen) {
610 outBuf += outCount;
611 outBufLen -= outCount;
612 } else {
613 /* halt output */
614 goto no_room;
615 }
616 }
617 break;
618 case EVENT_TYPE_LONG:
619 /* 64-bit signed long */
620 {
Jeff Brown44193d92015-04-28 12:47:02 -0700621 uint64_t lval;
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -0700622
623 if (eventDataLen < 8)
624 return -1;
Mark Salyzyn8470dad2015-03-06 20:42:57 +0000625 lval = get8LE(eventData);
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -0700626 eventData += 8;
627 eventDataLen -= 8;
628
Jeff Brown44193d92015-04-28 12:47:02 -0700629 outCount = snprintf(outBuf, outBufLen, "%" PRId64, lval);
630 if (outCount < outBufLen) {
631 outBuf += outCount;
632 outBufLen -= outCount;
633 } else {
634 /* halt output */
635 goto no_room;
636 }
637 }
638 break;
639 case EVENT_TYPE_FLOAT:
640 /* float */
641 {
642 uint32_t ival;
643 float fval;
644
645 if (eventDataLen < 4)
646 return -1;
647 ival = get4LE(eventData);
648 fval = *(float*)&ival;
649 eventData += 4;
650 eventDataLen -= 4;
651
652 outCount = snprintf(outBuf, outBufLen, "%f", fval);
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -0700653 if (outCount < outBufLen) {
654 outBuf += outCount;
655 outBufLen -= outCount;
656 } else {
657 /* halt output */
658 goto no_room;
659 }
660 }
661 break;
662 case EVENT_TYPE_STRING:
663 /* UTF-8 chars, not NULL-terminated */
664 {
665 unsigned int strLen;
666
667 if (eventDataLen < 4)
668 return -1;
Mark Salyzyn8470dad2015-03-06 20:42:57 +0000669 strLen = get4LE(eventData);
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -0700670 eventData += 4;
671 eventDataLen -= 4;
672
673 if (eventDataLen < strLen)
674 return -1;
675
676 if (strLen < outBufLen) {
677 memcpy(outBuf, eventData, strLen);
678 outBuf += strLen;
679 outBufLen -= strLen;
680 } else if (outBufLen > 0) {
681 /* copy what we can */
682 memcpy(outBuf, eventData, outBufLen);
683 outBuf += outBufLen;
684 outBufLen -= outBufLen;
685 goto no_room;
686 }
687 eventData += strLen;
688 eventDataLen -= strLen;
689 break;
690 }
691 case EVENT_TYPE_LIST:
692 /* N items, all different types */
693 {
694 unsigned char count;
695 int i;
696
697 if (eventDataLen < 1)
698 return -1;
699
700 count = *eventData++;
701 eventDataLen--;
702
703 if (outBufLen > 0) {
704 *outBuf++ = '[';
705 outBufLen--;
706 } else {
707 goto no_room;
708 }
709
710 for (i = 0; i < count; i++) {
711 result = android_log_printBinaryEvent(&eventData, &eventDataLen,
712 &outBuf, &outBufLen);
713 if (result != 0)
714 goto bail;
715
716 if (i < count-1) {
717 if (outBufLen > 0) {
718 *outBuf++ = ',';
719 outBufLen--;
720 } else {
721 goto no_room;
722 }
723 }
724 }
725
726 if (outBufLen > 0) {
727 *outBuf++ = ']';
728 outBufLen--;
729 } else {
730 goto no_room;
731 }
732 }
733 break;
734 default:
735 fprintf(stderr, "Unknown binary event type %d\n", type);
736 return -1;
737 }
738
739bail:
740 *pEventData = eventData;
741 *pEventDataLen = eventDataLen;
742 *pOutBuf = outBuf;
743 *pOutBufLen = outBufLen;
744 return result;
745
746no_room:
747 result = 1;
748 goto bail;
749}
750
751/**
752 * Convert a binary log entry to ASCII form.
753 *
754 * For convenience we mimic the processLogBuffer API. There is no
755 * pre-defined output length for the binary data, since we're free to format
756 * it however we choose, which means we can't really use a fixed-size buffer
757 * here.
758 */
Mark Salyzynbe1d3c22016-03-10 08:25:33 -0800759LIBLOG_ABI_PUBLIC int android_log_processBinaryLogBuffer(
760 struct logger_entry *buf,
761 AndroidLogEntry *entry,
762 const EventTagMap *map,
763 char *messageBuf, int messageBufLen)
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -0700764{
765 size_t inCount;
766 unsigned int tagIndex;
767 const unsigned char* eventData;
768
769 entry->tv_sec = buf->sec;
770 entry->tv_nsec = buf->nsec;
771 entry->priority = ANDROID_LOG_INFO;
Mark Salyzyn90e7af32015-12-07 16:52:42 -0800772 entry->uid = -1;
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -0700773 entry->pid = buf->pid;
774 entry->tid = buf->tid;
775
776 /*
Mark Salyzyn7bc80232015-12-11 12:32:53 -0800777 * Pull the tag out, fill in some additional details based on incoming
778 * buffer version (v3 adds lid, v4 adds uid).
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -0700779 */
780 eventData = (const unsigned char*) buf->msg;
Mark Salyzyn40b21552013-12-18 12:59:01 -0800781 struct logger_entry_v2 *buf2 = (struct logger_entry_v2 *)buf;
782 if (buf2->hdr_size) {
Mark Salyzyn305374c2016-08-18 14:59:41 -0700783 if ((buf2->hdr_size < sizeof(((struct log_msg *)NULL)->entry_v1)) ||
784 (buf2->hdr_size > sizeof(((struct log_msg *)NULL)->entry))) {
785 fprintf(stderr, "+++ LOG: entry illegal hdr_size\n");
786 return -1;
787 }
Mark Salyzyn40b21552013-12-18 12:59:01 -0800788 eventData = ((unsigned char *)buf2) + buf2->hdr_size;
Mark Salyzyn7bc80232015-12-11 12:32:53 -0800789 if ((buf2->hdr_size >= sizeof(struct logger_entry_v3)) &&
790 (((struct logger_entry_v3 *)buf)->lid == LOG_ID_SECURITY)) {
791 entry->priority = ANDROID_LOG_WARN;
792 }
Mark Salyzyn90e7af32015-12-07 16:52:42 -0800793 if (buf2->hdr_size >= sizeof(struct logger_entry_v4)) {
794 entry->uid = ((struct logger_entry_v4 *)buf)->uid;
795 }
Mark Salyzyn40b21552013-12-18 12:59:01 -0800796 }
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -0700797 inCount = buf->len;
798 if (inCount < 4)
799 return -1;
Mark Salyzyn8470dad2015-03-06 20:42:57 +0000800 tagIndex = get4LE(eventData);
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -0700801 eventData += 4;
802 inCount -= 4;
803
804 if (map != NULL) {
805 entry->tag = android_lookupEventTag(map, tagIndex);
806 } else {
807 entry->tag = NULL;
808 }
809
810 /*
811 * If we don't have a map, or didn't find the tag number in the map,
812 * stuff a generated tag value into the start of the output buffer and
813 * shift the buffer pointers down.
814 */
815 if (entry->tag == NULL) {
816 int tagLen;
817
818 tagLen = snprintf(messageBuf, messageBufLen, "[%d]", tagIndex);
819 entry->tag = messageBuf;
820 messageBuf += tagLen+1;
821 messageBufLen -= tagLen+1;
822 }
823
824 /*
825 * Format the event log data into the buffer.
826 */
827 char* outBuf = messageBuf;
828 size_t outRemaining = messageBufLen-1; /* leave one for nul byte */
829 int result;
830 result = android_log_printBinaryEvent(&eventData, &inCount, &outBuf,
831 &outRemaining);
832 if (result < 0) {
833 fprintf(stderr, "Binary log entry conversion failed\n");
834 return -1;
835 } else if (result == 1) {
836 if (outBuf > messageBuf) {
837 /* leave an indicator */
838 *(outBuf-1) = '!';
839 } else {
840 /* no room to output anything at all */
841 *outBuf++ = '!';
842 outRemaining--;
843 }
844 /* pretend we ate all the data */
845 inCount = 0;
846 }
847
848 /* eat the silly terminating '\n' */
849 if (inCount == 1 && *eventData == '\n') {
850 eventData++;
851 inCount--;
852 }
853
854 if (inCount != 0) {
855 fprintf(stderr,
Andrew Hsiehd2c8f522012-02-27 16:48:18 -0800856 "Warning: leftover binary log data (%zu bytes)\n", inCount);
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -0700857 }
858
859 /*
860 * Terminate the buffer. The NUL byte does not count as part of
861 * entry->messageLen.
862 */
863 *outBuf = '\0';
864 entry->messageLen = outBuf - messageBuf;
865 assert(entry->messageLen == (messageBufLen-1) - outRemaining);
866
867 entry->message = messageBuf;
868
869 return 0;
870}
871
Mark Salyzynb932b2f2015-05-15 09:01:58 -0700872/*
873 * One utf8 character at a time
874 *
875 * Returns the length of the utf8 character in the buffer,
876 * or -1 if illegal or truncated
877 *
878 * Open coded from libutils/Unicode.cpp, borrowed from utf8_length(),
879 * can not remove from here because of library circular dependencies.
880 * Expect one-day utf8_character_length with the same signature could
881 * _also_ be part of libutils/Unicode.cpp if its usefullness needs to
882 * propagate globally.
883 */
Mark Salyzynbe1d3c22016-03-10 08:25:33 -0800884LIBLOG_WEAK ssize_t utf8_character_length(const char *src, size_t len)
Mark Salyzynb932b2f2015-05-15 09:01:58 -0700885{
886 const char *cur = src;
887 const char first_char = *cur++;
888 static const uint32_t kUnicodeMaxCodepoint = 0x0010FFFF;
889 int32_t mask, to_ignore_mask;
890 size_t num_to_read;
891 uint32_t utf32;
892
893 if ((first_char & 0x80) == 0) { /* ASCII */
Mark Salyzynfaa92e92015-09-08 07:57:27 -0700894 return first_char ? 1 : -1;
Mark Salyzynb932b2f2015-05-15 09:01:58 -0700895 }
896
897 /*
898 * (UTF-8's character must not be like 10xxxxxx,
899 * but 110xxxxx, 1110xxxx, ... or 1111110x)
900 */
901 if ((first_char & 0x40) == 0) {
902 return -1;
903 }
904
905 for (utf32 = 1, num_to_read = 1, mask = 0x40, to_ignore_mask = 0x80;
906 num_to_read < 5 && (first_char & mask);
907 num_to_read++, to_ignore_mask |= mask, mask >>= 1) {
908 if (num_to_read > len) {
909 return -1;
910 }
911 if ((*cur & 0xC0) != 0x80) { /* can not be 10xxxxxx? */
912 return -1;
913 }
914 utf32 = (utf32 << 6) + (*cur++ & 0b00111111);
915 }
916 /* "first_char" must be (110xxxxx - 11110xxx) */
917 if (num_to_read >= 5) {
918 return -1;
919 }
920 to_ignore_mask |= mask;
921 utf32 |= ((~to_ignore_mask) & first_char) << (6 * (num_to_read - 1));
922 if (utf32 > kUnicodeMaxCodepoint) {
923 return -1;
924 }
925 return num_to_read;
926}
927
928/*
929 * Convert to printable from message to p buffer, return string length. If p is
930 * NULL, do not copy, but still return the expected string length.
931 */
932static size_t convertPrintable(char *p, const char *message, size_t messageLen)
933{
934 char *begin = p;
935 bool print = p != NULL;
936
937 while (messageLen) {
938 char buf[6];
939 ssize_t len = sizeof(buf) - 1;
940 if ((size_t)len > messageLen) {
941 len = messageLen;
942 }
943 len = utf8_character_length(message, len);
944
945 if (len < 0) {
946 snprintf(buf, sizeof(buf),
947 ((messageLen > 1) && isdigit(message[1]))
948 ? "\\%03o"
949 : "\\%o",
950 *message & 0377);
951 len = 1;
952 } else {
953 buf[0] = '\0';
954 if (len == 1) {
955 if (*message == '\a') {
956 strcpy(buf, "\\a");
957 } else if (*message == '\b') {
958 strcpy(buf, "\\b");
959 } else if (*message == '\t') {
Mark Salyzyn65d5ca22015-11-18 09:58:00 -0800960 strcpy(buf, "\t"); // Do not escape tabs
Mark Salyzynb932b2f2015-05-15 09:01:58 -0700961 } else if (*message == '\v') {
962 strcpy(buf, "\\v");
963 } else if (*message == '\f') {
964 strcpy(buf, "\\f");
965 } else if (*message == '\r') {
966 strcpy(buf, "\\r");
967 } else if (*message == '\\') {
968 strcpy(buf, "\\\\");
969 } else if ((*message < ' ') || (*message & 0x80)) {
970 snprintf(buf, sizeof(buf), "\\%o", *message & 0377);
971 }
972 }
973 if (!buf[0]) {
974 strncpy(buf, message, len);
975 buf[len] = '\0';
976 }
977 }
978 if (print) {
979 strcpy(p, buf);
980 }
981 p += strlen(buf);
982 message += len;
983 messageLen -= len;
984 }
985 return p - begin;
986}
987
Mark Salyzynbe1d3c22016-03-10 08:25:33 -0800988static char *readSeconds(char *e, struct timespec *t)
Mark Salyzyn4cbed022015-08-31 15:53:41 -0700989{
990 unsigned long multiplier;
991 char *p;
992 t->tv_sec = strtoul(e, &p, 10);
993 if (*p != '.') {
994 return NULL;
995 }
996 t->tv_nsec = 0;
997 multiplier = NS_PER_SEC;
998 while (isdigit(*++p) && (multiplier /= 10)) {
999 t->tv_nsec += (*p - '0') * multiplier;
1000 }
1001 return p;
1002}
1003
1004static struct timespec *sumTimespec(struct timespec *left,
1005 struct timespec *right)
1006{
1007 left->tv_nsec += right->tv_nsec;
1008 left->tv_sec += right->tv_sec;
1009 if (left->tv_nsec >= (long)NS_PER_SEC) {
1010 left->tv_nsec -= NS_PER_SEC;
1011 left->tv_sec += 1;
1012 }
1013 return left;
1014}
1015
1016static struct timespec *subTimespec(struct timespec *result,
1017 struct timespec *left,
1018 struct timespec *right)
1019{
1020 result->tv_nsec = left->tv_nsec - right->tv_nsec;
1021 result->tv_sec = left->tv_sec - right->tv_sec;
1022 if (result->tv_nsec < 0) {
1023 result->tv_nsec += NS_PER_SEC;
1024 result->tv_sec -= 1;
1025 }
1026 return result;
1027}
1028
1029static long long nsecTimespec(struct timespec *now)
1030{
1031 return (long long)now->tv_sec * NS_PER_SEC + now->tv_nsec;
1032}
1033
1034static void convertMonotonic(struct timespec *result,
1035 const AndroidLogEntry *entry)
1036{
1037 struct listnode *node;
1038 struct conversionList {
1039 struct listnode node; /* first */
1040 struct timespec time;
1041 struct timespec convert;
1042 } *list, *next;
1043 struct timespec time, convert;
1044
1045 /* If we do not have a conversion list, build one up */
1046 if (list_empty(&convertHead)) {
1047 bool suspended_pending = false;
1048 struct timespec suspended_monotonic = { 0, 0 };
1049 struct timespec suspended_diff = { 0, 0 };
1050
1051 /*
1052 * Read dmesg for _some_ synchronization markers and insert
1053 * Anything in the Android Logger before the dmesg logging span will
1054 * be highly suspect regarding the monotonic time calculations.
1055 */
Mark Salyzyn78786da2016-04-28 16:06:24 -07001056 FILE *p = popen("/system/bin/dmesg", "re");
Mark Salyzyn4cbed022015-08-31 15:53:41 -07001057 if (p) {
1058 char *line = NULL;
1059 size_t len = 0;
1060 while (getline(&line, &len, p) > 0) {
1061 static const char suspend[] = "PM: suspend entry ";
1062 static const char resume[] = "PM: suspend exit ";
1063 static const char healthd[] = "healthd";
1064 static const char battery[] = ": battery ";
1065 static const char suspended[] = "Suspended for ";
1066 struct timespec monotonic;
1067 struct tm tm;
1068 char *cp, *e = line;
1069 bool add_entry = true;
1070
1071 if (*e == '<') {
1072 while (*e && (*e != '>')) {
1073 ++e;
1074 }
1075 if (*e != '>') {
1076 continue;
1077 }
1078 }
1079 if (*e != '[') {
1080 continue;
1081 }
1082 while (*++e == ' ') {
1083 ;
1084 }
1085 e = readSeconds(e, &monotonic);
1086 if (!e || (*e != ']')) {
1087 continue;
1088 }
1089
1090 if ((e = strstr(e, suspend))) {
1091 e += sizeof(suspend) - 1;
1092 } else if ((e = strstr(line, resume))) {
1093 e += sizeof(resume) - 1;
1094 } else if (((e = strstr(line, healthd)))
1095 && ((e = strstr(e + sizeof(healthd) - 1, battery)))) {
1096 /* NB: healthd is roughly 150us late, worth the price to
1097 * deal with ntp-induced or hardware clock drift. */
1098 e += sizeof(battery) - 1;
1099 } else if ((e = strstr(line, suspended))) {
1100 e += sizeof(suspended) - 1;
1101 e = readSeconds(e, &time);
1102 if (!e) {
1103 continue;
1104 }
1105 add_entry = false;
1106 suspended_pending = true;
1107 suspended_monotonic = monotonic;
1108 suspended_diff = time;
1109 } else {
1110 continue;
1111 }
1112 if (add_entry) {
1113 /* look for "????-??-?? ??:??:??.????????? UTC" */
1114 cp = strstr(e, " UTC");
1115 if (!cp || ((cp - e) < 29) || (cp[-10] != '.')) {
1116 continue;
1117 }
1118 e = cp - 29;
1119 cp = readSeconds(cp - 10, &time);
1120 if (!cp) {
1121 continue;
1122 }
1123 cp = strptime(e, "%Y-%m-%d %H:%M:%S.", &tm);
1124 if (!cp) {
1125 continue;
1126 }
1127 cp = getenv(tz);
1128 if (cp) {
1129 cp = strdup(cp);
1130 }
1131 setenv(tz, utc, 1);
1132 time.tv_sec = mktime(&tm);
1133 if (cp) {
1134 setenv(tz, cp, 1);
1135 free(cp);
1136 } else {
1137 unsetenv(tz);
1138 }
1139 list = calloc(1, sizeof(struct conversionList));
1140 list_init(&list->node);
1141 list->time = time;
1142 subTimespec(&list->convert, &time, &monotonic);
1143 list_add_tail(&convertHead, &list->node);
1144 }
1145 if (suspended_pending && !list_empty(&convertHead)) {
1146 list = node_to_item(list_tail(&convertHead),
1147 struct conversionList, node);
1148 if (subTimespec(&time,
1149 subTimespec(&time,
1150 &list->time,
1151 &list->convert),
1152 &suspended_monotonic)->tv_sec > 0) {
1153 /* resume, what is convert factor before? */
1154 subTimespec(&convert, &list->convert, &suspended_diff);
1155 } else {
1156 /* suspend */
1157 convert = list->convert;
1158 }
1159 time = suspended_monotonic;
1160 sumTimespec(&time, &convert);
1161 /* breakpoint just before sleep */
1162 list = calloc(1, sizeof(struct conversionList));
1163 list_init(&list->node);
1164 list->time = time;
1165 list->convert = convert;
1166 list_add_tail(&convertHead, &list->node);
1167 /* breakpoint just after sleep */
1168 list = calloc(1, sizeof(struct conversionList));
1169 list_init(&list->node);
1170 list->time = time;
1171 sumTimespec(&list->time, &suspended_diff);
1172 list->convert = convert;
1173 sumTimespec(&list->convert, &suspended_diff);
1174 list_add_tail(&convertHead, &list->node);
1175 suspended_pending = false;
1176 }
1177 }
1178 pclose(p);
1179 }
1180 /* last entry is our current time conversion */
1181 list = calloc(1, sizeof(struct conversionList));
1182 list_init(&list->node);
1183 clock_gettime(CLOCK_REALTIME, &list->time);
1184 clock_gettime(CLOCK_MONOTONIC, &convert);
1185 clock_gettime(CLOCK_MONOTONIC, &time);
1186 /* Correct for instant clock_gettime latency (syscall or ~30ns) */
1187 subTimespec(&time, &convert, subTimespec(&time, &time, &convert));
1188 /* Calculate conversion factor */
1189 subTimespec(&list->convert, &list->time, &time);
1190 list_add_tail(&convertHead, &list->node);
1191 if (suspended_pending) {
1192 /* manufacture a suspend @ point before */
1193 subTimespec(&convert, &list->convert, &suspended_diff);
1194 time = suspended_monotonic;
1195 sumTimespec(&time, &convert);
1196 /* breakpoint just after sleep */
1197 list = calloc(1, sizeof(struct conversionList));
1198 list_init(&list->node);
1199 list->time = time;
1200 sumTimespec(&list->time, &suspended_diff);
1201 list->convert = convert;
1202 sumTimespec(&list->convert, &suspended_diff);
1203 list_add_head(&convertHead, &list->node);
1204 /* breakpoint just before sleep */
1205 list = calloc(1, sizeof(struct conversionList));
1206 list_init(&list->node);
1207 list->time = time;
1208 list->convert = convert;
1209 list_add_head(&convertHead, &list->node);
1210 }
1211 }
1212
1213 /* Find the breakpoint in the conversion list */
1214 list = node_to_item(list_head(&convertHead), struct conversionList, node);
1215 next = NULL;
1216 list_for_each(node, &convertHead) {
1217 next = node_to_item(node, struct conversionList, node);
1218 if (entry->tv_sec < next->time.tv_sec) {
1219 break;
1220 } else if (entry->tv_sec == next->time.tv_sec) {
1221 if (entry->tv_nsec < next->time.tv_nsec) {
1222 break;
1223 }
1224 }
1225 list = next;
1226 }
1227
1228 /* blend time from one breakpoint to the next */
1229 convert = list->convert;
1230 if (next) {
1231 unsigned long long total, run;
1232
1233 total = nsecTimespec(subTimespec(&time, &next->time, &list->time));
1234 time.tv_sec = entry->tv_sec;
1235 time.tv_nsec = entry->tv_nsec;
1236 run = nsecTimespec(subTimespec(&time, &time, &list->time));
1237 if (run < total) {
1238 long long crun;
1239
1240 float f = nsecTimespec(subTimespec(&time, &next->convert, &convert));
1241 f *= run;
1242 f /= total;
1243 crun = f;
1244 convert.tv_sec += crun / (long long)NS_PER_SEC;
1245 if (crun < 0) {
1246 convert.tv_nsec -= (-crun) % NS_PER_SEC;
1247 if (convert.tv_nsec < 0) {
1248 convert.tv_nsec += NS_PER_SEC;
1249 convert.tv_sec -= 1;
1250 }
1251 } else {
1252 convert.tv_nsec += crun % NS_PER_SEC;
1253 if (convert.tv_nsec >= (long)NS_PER_SEC) {
1254 convert.tv_nsec -= NS_PER_SEC;
1255 convert.tv_sec += 1;
1256 }
1257 }
1258 }
1259 }
1260
1261 /* Apply the correction factor */
1262 result->tv_sec = entry->tv_sec;
1263 result->tv_nsec = entry->tv_nsec;
1264 subTimespec(result, result, &convert);
1265}
1266
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -07001267/**
1268 * Formats a log message into a buffer
1269 *
1270 * Uses defaultBuffer if it can, otherwise malloc()'s a new buffer
1271 * If return value != defaultBuffer, caller must call free()
1272 * Returns NULL on malloc error
1273 */
1274
Mark Salyzynbe1d3c22016-03-10 08:25:33 -08001275LIBLOG_ABI_PUBLIC char *android_log_formatLogLine (
1276 AndroidLogFormat *p_format,
1277 char *defaultBuffer,
1278 size_t defaultBufferSize,
1279 const AndroidLogEntry *entry,
1280 size_t *p_outLength)
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -07001281{
Yabin Cui8a985352014-11-13 10:02:08 -08001282#if !defined(_WIN32)
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -07001283 struct tm tmBuf;
1284#endif
1285 struct tm* ptm;
Mark Salyzynf28f6a92015-08-31 08:01:33 -07001286 char timeBuf[64]; /* good margin, 23+nul for msec, 26+nul for usec */
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -07001287 char prefixBuf[128], suffixBuf[128];
1288 char priChar;
1289 int prefixSuffixIsHeaderFooter = 0;
Mark Salyzyn90e7af32015-12-07 16:52:42 -08001290 char *ret;
Mark Salyzyn4cbed022015-08-31 15:53:41 -07001291 time_t now;
1292 unsigned long nsec;
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -07001293
1294 priChar = filterPriToChar(entry->priority);
Pierre Zurekead88fc2010-10-17 22:39:37 +02001295 size_t prefixLen = 0, suffixLen = 0;
1296 size_t len;
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -07001297
1298 /*
1299 * Get the current date/time in pretty form
1300 *
1301 * It's often useful when examining a log with "less" to jump to
1302 * a specific point in the file by searching for the date/time stamp.
1303 * For this reason it's very annoying to have regexp meta characters
1304 * in the time stamp. Don't use forward slashes, parenthesis,
1305 * brackets, asterisks, or other special chars here.
Mark Salyzynf28f6a92015-08-31 08:01:33 -07001306 *
1307 * The caller may have affected the timezone environment, this is
1308 * expected to be sensitive to that.
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -07001309 */
Mark Salyzyn4cbed022015-08-31 15:53:41 -07001310 now = entry->tv_sec;
1311 nsec = entry->tv_nsec;
1312 if (p_format->monotonic_output) {
Mark Salyzynb6bee332015-09-08 08:56:32 -07001313 // prevent convertMonotonic from being called if logd is monotonic
Mark Salyzynba7a9a02015-12-01 15:57:25 -08001314 if (android_log_clockid() != CLOCK_MONOTONIC) {
Mark Salyzynb6bee332015-09-08 08:56:32 -07001315 struct timespec time;
1316 convertMonotonic(&time, entry);
1317 now = time.tv_sec;
1318 nsec = time.tv_nsec;
1319 }
Mark Salyzyn4cbed022015-08-31 15:53:41 -07001320 }
1321 if (now < 0) {
1322 nsec = NS_PER_SEC - nsec;
1323 }
1324 if (p_format->epoch_output || p_format->monotonic_output) {
1325 ptm = NULL;
1326 snprintf(timeBuf, sizeof(timeBuf),
1327 p_format->monotonic_output ? "%6lld" : "%19lld",
1328 (long long)now);
1329 } else {
Yabin Cui8a985352014-11-13 10:02:08 -08001330#if !defined(_WIN32)
Mark Salyzyn4cbed022015-08-31 15:53:41 -07001331 ptm = localtime_r(&now, &tmBuf);
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -07001332#else
Mark Salyzyn4cbed022015-08-31 15:53:41 -07001333 ptm = localtime(&now);
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -07001334#endif
Mark Salyzyn4cbed022015-08-31 15:53:41 -07001335 strftime(timeBuf, sizeof(timeBuf),
1336 &"%Y-%m-%d %H:%M:%S"[p_format->year_output ? 0 : 3],
1337 ptm);
1338 }
Mark Salyzyne1f20042015-05-06 08:40:40 -07001339 len = strlen(timeBuf);
1340 if (p_format->usec_time_output) {
Mark Salyzynf28f6a92015-08-31 08:01:33 -07001341 len += snprintf(timeBuf + len, sizeof(timeBuf) - len,
Mark Salyzyn4cbed022015-08-31 15:53:41 -07001342 ".%06ld", nsec / US_PER_NSEC);
Mark Salyzyne1f20042015-05-06 08:40:40 -07001343 } else {
Mark Salyzynf28f6a92015-08-31 08:01:33 -07001344 len += snprintf(timeBuf + len, sizeof(timeBuf) - len,
Mark Salyzyn4cbed022015-08-31 15:53:41 -07001345 ".%03ld", nsec / MS_PER_NSEC);
Mark Salyzynf28f6a92015-08-31 08:01:33 -07001346 }
Mark Salyzyn4cbed022015-08-31 15:53:41 -07001347 if (p_format->zone_output && ptm) {
Mark Salyzynf28f6a92015-08-31 08:01:33 -07001348 strftime(timeBuf + len, sizeof(timeBuf) - len, " %z", ptm);
Mark Salyzyne1f20042015-05-06 08:40:40 -07001349 }
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -07001350
1351 /*
1352 * Construct a buffer containing the log header and log message.
1353 */
Pierre Zurekead88fc2010-10-17 22:39:37 +02001354 if (p_format->colored_output) {
1355 prefixLen = snprintf(prefixBuf, sizeof(prefixBuf), "\x1B[38;5;%dm",
1356 colorFromPri(entry->priority));
1357 prefixLen = MIN(prefixLen, sizeof(prefixBuf));
1358 suffixLen = snprintf(suffixBuf, sizeof(suffixBuf), "\x1B[0m");
1359 suffixLen = MIN(suffixLen, sizeof(suffixBuf));
1360 }
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -07001361
Mark Salyzyn90e7af32015-12-07 16:52:42 -08001362 char uid[16];
1363 uid[0] = '\0';
1364 if (p_format->uid_output) {
1365 if (entry->uid >= 0) {
Mark Salyzyn2aa510e2015-12-08 09:15:06 -08001366
William Roberts8a5b9ca2016-04-08 12:13:17 -07001367 /*
1368 * This code is Android specific, bionic guarantees that
1369 * calls to non-reentrant getpwuid() are thread safe.
1370 */
1371#ifndef __BIONIC__
1372#warning "This code assumes that getpwuid is thread safe, only true with Bionic!"
1373#endif
1374 struct passwd* pwd = getpwuid(entry->uid);
1375 if (pwd && (strlen(pwd->pw_name) <= 5)) {
1376 snprintf(uid, sizeof(uid), "%5s:", pwd->pw_name);
Mark Salyzyn2aa510e2015-12-08 09:15:06 -08001377 } else {
1378 // Not worth parsing package list, names all longer than 5
1379 snprintf(uid, sizeof(uid), "%5d:", entry->uid);
1380 }
Mark Salyzyn90e7af32015-12-07 16:52:42 -08001381 } else {
1382 snprintf(uid, sizeof(uid), " ");
1383 }
1384 }
1385
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -07001386 switch (p_format->format) {
1387 case FORMAT_TAG:
Pierre Zurekead88fc2010-10-17 22:39:37 +02001388 len = snprintf(prefixBuf + prefixLen, sizeof(prefixBuf) - prefixLen,
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -07001389 "%c/%-8s: ", priChar, entry->tag);
Pierre Zurekead88fc2010-10-17 22:39:37 +02001390 strcpy(suffixBuf + suffixLen, "\n");
1391 ++suffixLen;
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -07001392 break;
1393 case FORMAT_PROCESS:
Pierre Zurekead88fc2010-10-17 22:39:37 +02001394 len = snprintf(suffixBuf + suffixLen, sizeof(suffixBuf) - suffixLen,
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -07001395 " (%s)\n", entry->tag);
Pierre Zurekead88fc2010-10-17 22:39:37 +02001396 suffixLen += MIN(len, sizeof(suffixBuf) - suffixLen);
1397 len = snprintf(prefixBuf + prefixLen, sizeof(prefixBuf) - prefixLen,
Mark Salyzyn90e7af32015-12-07 16:52:42 -08001398 "%c(%s%5d) ", priChar, uid, entry->pid);
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -07001399 break;
1400 case FORMAT_THREAD:
Pierre Zurekead88fc2010-10-17 22:39:37 +02001401 len = snprintf(prefixBuf + prefixLen, sizeof(prefixBuf) - prefixLen,
Mark Salyzyn90e7af32015-12-07 16:52:42 -08001402 "%c(%s%5d:%5d) ", priChar, uid, entry->pid, entry->tid);
Pierre Zurekead88fc2010-10-17 22:39:37 +02001403 strcpy(suffixBuf + suffixLen, "\n");
1404 ++suffixLen;
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -07001405 break;
1406 case FORMAT_RAW:
Pierre Zurekead88fc2010-10-17 22:39:37 +02001407 prefixBuf[prefixLen] = 0;
1408 len = 0;
1409 strcpy(suffixBuf + suffixLen, "\n");
1410 ++suffixLen;
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -07001411 break;
1412 case FORMAT_TIME:
Pierre Zurekead88fc2010-10-17 22:39:37 +02001413 len = snprintf(prefixBuf + prefixLen, sizeof(prefixBuf) - prefixLen,
Mark Salyzyn90e7af32015-12-07 16:52:42 -08001414 "%s %c/%-8s(%s%5d): ", timeBuf, priChar, entry->tag,
1415 uid, entry->pid);
Pierre Zurekead88fc2010-10-17 22:39:37 +02001416 strcpy(suffixBuf + suffixLen, "\n");
1417 ++suffixLen;
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -07001418 break;
1419 case FORMAT_THREADTIME:
Mark Salyzyn90e7af32015-12-07 16:52:42 -08001420 ret = strchr(uid, ':');
1421 if (ret) {
1422 *ret = ' ';
1423 }
Pierre Zurekead88fc2010-10-17 22:39:37 +02001424 len = snprintf(prefixBuf + prefixLen, sizeof(prefixBuf) - prefixLen,
Mark Salyzyn90e7af32015-12-07 16:52:42 -08001425 "%s %s%5d %5d %c %-8s: ", timeBuf,
1426 uid, entry->pid, entry->tid, priChar, entry->tag);
Pierre Zurekead88fc2010-10-17 22:39:37 +02001427 strcpy(suffixBuf + suffixLen, "\n");
1428 ++suffixLen;
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -07001429 break;
1430 case FORMAT_LONG:
Pierre Zurekead88fc2010-10-17 22:39:37 +02001431 len = snprintf(prefixBuf + prefixLen, sizeof(prefixBuf) - prefixLen,
Mark Salyzyn90e7af32015-12-07 16:52:42 -08001432 "[ %s %s%5d:%5d %c/%-8s ]\n",
1433 timeBuf, uid, entry->pid, entry->tid, priChar, entry->tag);
Pierre Zurekead88fc2010-10-17 22:39:37 +02001434 strcpy(suffixBuf + suffixLen, "\n\n");
1435 suffixLen += 2;
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -07001436 prefixSuffixIsHeaderFooter = 1;
1437 break;
1438 case FORMAT_BRIEF:
1439 default:
Pierre Zurekead88fc2010-10-17 22:39:37 +02001440 len = snprintf(prefixBuf + prefixLen, sizeof(prefixBuf) - prefixLen,
Mark Salyzyn90e7af32015-12-07 16:52:42 -08001441 "%c/%-8s(%s%5d): ", priChar, entry->tag, uid, entry->pid);
Pierre Zurekead88fc2010-10-17 22:39:37 +02001442 strcpy(suffixBuf + suffixLen, "\n");
1443 ++suffixLen;
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -07001444 break;
1445 }
Pierre Zurekead88fc2010-10-17 22:39:37 +02001446
Keith Prestonb45b5c92010-02-11 15:12:53 -06001447 /* snprintf has a weird return value. It returns what would have been
1448 * written given a large enough buffer. In the case that the prefix is
1449 * longer then our buffer(128), it messes up the calculations below
1450 * possibly causing heap corruption. To avoid this we double check and
1451 * set the length at the maximum (size minus null byte)
1452 */
Mark Salyzyn2f83d672016-03-11 12:06:12 -08001453 prefixLen += len;
1454 if (prefixLen >= sizeof(prefixBuf)) {
1455 prefixLen = sizeof(prefixBuf) - 1;
1456 prefixBuf[sizeof(prefixBuf) - 1] = '\0';
1457 }
1458 if (suffixLen >= sizeof(suffixBuf)) {
1459 suffixLen = sizeof(suffixBuf) - 1;
1460 suffixBuf[sizeof(suffixBuf) - 2] = '\n';
1461 suffixBuf[sizeof(suffixBuf) - 1] = '\0';
1462 }
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -07001463
1464 /* the following code is tragically unreadable */
1465
1466 size_t numLines;
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -07001467 char *p;
1468 size_t bufferSize;
1469 const char *pm;
1470
1471 if (prefixSuffixIsHeaderFooter) {
Mark Salyzynb932b2f2015-05-15 09:01:58 -07001472 /* we're just wrapping message with a header/footer */
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -07001473 numLines = 1;
1474 } else {
1475 pm = entry->message;
1476 numLines = 0;
1477
Mark Salyzynb932b2f2015-05-15 09:01:58 -07001478 /*
1479 * The line-end finding here must match the line-end finding
1480 * in for ( ... numLines...) loop below
1481 */
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -07001482 while (pm < (entry->message + entry->messageLen)) {
1483 if (*pm++ == '\n') numLines++;
1484 }
Mark Salyzynb932b2f2015-05-15 09:01:58 -07001485 /* plus one line for anything not newline-terminated at the end */
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -07001486 if (pm > entry->message && *(pm-1) != '\n') numLines++;
1487 }
1488
Mark Salyzynb932b2f2015-05-15 09:01:58 -07001489 /*
1490 * this is an upper bound--newlines in message may be counted
1491 * extraneously
1492 */
1493 bufferSize = (numLines * (prefixLen + suffixLen)) + 1;
1494 if (p_format->printable_output) {
1495 /* Calculate extra length to convert non-printable to printable */
1496 bufferSize += convertPrintable(NULL, entry->message, entry->messageLen);
1497 } else {
1498 bufferSize += entry->messageLen;
1499 }
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -07001500
1501 if (defaultBufferSize >= bufferSize) {
1502 ret = defaultBuffer;
1503 } else {
1504 ret = (char *)malloc(bufferSize);
1505
1506 if (ret == NULL) {
1507 return ret;
1508 }
1509 }
1510
1511 ret[0] = '\0'; /* to start strcat off */
1512
1513 p = ret;
1514 pm = entry->message;
1515
1516 if (prefixSuffixIsHeaderFooter) {
1517 strcat(p, prefixBuf);
1518 p += prefixLen;
Mark Salyzynb932b2f2015-05-15 09:01:58 -07001519 if (p_format->printable_output) {
1520 p += convertPrintable(p, entry->message, entry->messageLen);
1521 } else {
1522 strncat(p, entry->message, entry->messageLen);
1523 p += entry->messageLen;
1524 }
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -07001525 strcat(p, suffixBuf);
1526 p += suffixLen;
1527 } else {
Mark Salyzyn7cc80132016-01-20 13:52:46 -08001528 do {
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -07001529 const char *lineStart;
1530 size_t lineLen;
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -07001531 lineStart = pm;
1532
Mark Salyzynb932b2f2015-05-15 09:01:58 -07001533 /* Find the next end-of-line in message */
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -07001534 while (pm < (entry->message + entry->messageLen)
1535 && *pm != '\n') pm++;
1536 lineLen = pm - lineStart;
1537
1538 strcat(p, prefixBuf);
1539 p += prefixLen;
Mark Salyzynb932b2f2015-05-15 09:01:58 -07001540 if (p_format->printable_output) {
1541 p += convertPrintable(p, lineStart, lineLen);
1542 } else {
1543 strncat(p, lineStart, lineLen);
1544 p += lineLen;
1545 }
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -07001546 strcat(p, suffixBuf);
1547 p += suffixLen;
1548
1549 if (*pm == '\n') pm++;
Mark Salyzyn7cc80132016-01-20 13:52:46 -08001550 } while (pm < (entry->message + entry->messageLen));
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -07001551 }
1552
1553 if (p_outLength != NULL) {
1554 *p_outLength = p - ret;
1555 }
1556
1557 return ret;
1558}
1559
1560/**
1561 * Either print or do not print log line, based on filter
1562 *
1563 * Returns count bytes written
1564 */
1565
Mark Salyzynbe1d3c22016-03-10 08:25:33 -08001566LIBLOG_ABI_PUBLIC int android_log_printLogLine(
1567 AndroidLogFormat *p_format,
1568 int fd,
1569 const AndroidLogEntry *entry)
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -07001570{
1571 int ret;
1572 char defaultBuffer[512];
1573 char *outBuffer = NULL;
1574 size_t totalLen;
1575
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -07001576 outBuffer = android_log_formatLogLine(p_format, defaultBuffer,
1577 sizeof(defaultBuffer), entry, &totalLen);
1578
1579 if (!outBuffer)
1580 return -1;
1581
1582 do {
1583 ret = write(fd, outBuffer, totalLen);
1584 } while (ret < 0 && errno == EINTR);
1585
1586 if (ret < 0) {
1587 fprintf(stderr, "+++ LOG: write failed (errno=%d)\n", errno);
1588 ret = 0;
1589 goto done;
1590 }
1591
1592 if (((size_t)ret) < totalLen) {
1593 fprintf(stderr, "+++ LOG: write partial (%d of %d)\n", ret,
1594 (int)totalLen);
1595 goto done;
1596 }
1597
1598done:
1599 if (outBuffer != defaultBuffer) {
1600 free(outBuffer);
1601 }
1602
1603 return ret;
1604}