blob: 59bd479175fd7f251fe3b21404529caaddb72a92 [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) {
499 msg = ((char *)buf2) + buf2->hdr_size;
Mark Salyzyn90e7af32015-12-07 16:52:42 -0800500 if (buf2->hdr_size >= sizeof(struct logger_entry_v4)) {
501 entry->uid = ((struct logger_entry_v4 *)buf)->uid;
502 }
Mark Salyzyn40b21552013-12-18 12:59:01 -0800503 }
Nick Kraleviche1ede152011-10-18 15:23:33 -0700504 for (i = 1; i < buf->len; i++) {
Mark Salyzyn40b21552013-12-18 12:59:01 -0800505 if (msg[i] == '\0') {
Jeff Sharkeya820a0e2011-10-26 18:40:39 -0700506 if (msgStart == -1) {
507 msgStart = i + 1;
508 } else {
509 msgEnd = i;
510 break;
511 }
Nick Kraleviche1ede152011-10-18 15:23:33 -0700512 }
513 }
Jeff Sharkeya820a0e2011-10-26 18:40:39 -0700514
515 if (msgStart == -1) {
Mark Salyzyn083c5342016-03-21 09:45:34 -0700516 /* +++ LOG: malformed log message, DYB */
517 for (i = 1; i < buf->len; i++) {
518 /* odd characters in tag? */
519 if ((msg[i] <= ' ') || (msg[i] == ':') || (msg[i] >= 0x7f)) {
520 msg[i] = '\0';
521 msgStart = i + 1;
522 break;
523 }
524 }
525 if (msgStart == -1) {
526 msgStart = buf->len - 1; /* All tag, no message, print truncates */
527 }
Nick Kralevich63f4a842011-10-17 10:45:03 -0700528 }
Jeff Sharkeya820a0e2011-10-26 18:40:39 -0700529 if (msgEnd == -1) {
Mark Salyzynb932b2f2015-05-15 09:01:58 -0700530 /* incoming message not null-terminated; force it */
Mark Salyzynd7bcf402015-12-04 09:24:15 -0800531 msgEnd = buf->len - 1; /* may result in msgEnd < msgStart */
Mark Salyzyn40b21552013-12-18 12:59:01 -0800532 msg[msgEnd] = '\0';
Jeff Sharkeya820a0e2011-10-26 18:40:39 -0700533 }
534
Mark Salyzyn40b21552013-12-18 12:59:01 -0800535 entry->priority = msg[0];
536 entry->tag = msg + 1;
537 entry->message = msg + msgStart;
Mark Salyzynd7bcf402015-12-04 09:24:15 -0800538 entry->messageLen = (msgEnd < msgStart) ? 0 : (msgEnd - msgStart);
Nick Kralevich63f4a842011-10-17 10:45:03 -0700539
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -0700540 return 0;
541}
542
543/*
Mark Salyzyn8470dad2015-03-06 20:42:57 +0000544 * Extract a 4-byte value from a byte stream.
545 */
546static inline uint32_t get4LE(const uint8_t* src)
547{
548 return src[0] | (src[1] << 8) | (src[2] << 16) | (src[3] << 24);
549}
550
551/*
552 * Extract an 8-byte value from a byte stream.
553 */
554static inline uint64_t get8LE(const uint8_t* src)
555{
556 uint32_t low, high;
557
558 low = src[0] | (src[1] << 8) | (src[2] << 16) | (src[3] << 24);
559 high = src[4] | (src[5] << 8) | (src[6] << 16) | (src[7] << 24);
Jeff Brown44193d92015-04-28 12:47:02 -0700560 return ((uint64_t) high << 32) | (uint64_t) low;
Mark Salyzyn8470dad2015-03-06 20:42:57 +0000561}
562
563
564/*
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -0700565 * Recursively convert binary log data to printable form.
566 *
567 * This needs to be recursive because you can have lists of lists.
568 *
569 * If we run out of room, we stop processing immediately. It's important
570 * for us to check for space on every output element to avoid producing
571 * garbled output.
572 *
573 * Returns 0 on success, 1 on buffer full, -1 on failure.
574 */
575static int android_log_printBinaryEvent(const unsigned char** pEventData,
576 size_t* pEventDataLen, char** pOutBuf, size_t* pOutBufLen)
577{
578 const unsigned char* eventData = *pEventData;
579 size_t eventDataLen = *pEventDataLen;
580 char* outBuf = *pOutBuf;
581 size_t outBufLen = *pOutBufLen;
582 unsigned char type;
583 size_t outCount;
584 int result = 0;
585
586 if (eventDataLen < 1)
587 return -1;
588 type = *eventData++;
589 eventDataLen--;
590
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -0700591 switch (type) {
592 case EVENT_TYPE_INT:
593 /* 32-bit signed int */
594 {
595 int ival;
596
597 if (eventDataLen < 4)
598 return -1;
Mark Salyzyn8470dad2015-03-06 20:42:57 +0000599 ival = get4LE(eventData);
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -0700600 eventData += 4;
601 eventDataLen -= 4;
602
603 outCount = snprintf(outBuf, outBufLen, "%d", ival);
604 if (outCount < outBufLen) {
605 outBuf += outCount;
606 outBufLen -= outCount;
607 } else {
608 /* halt output */
609 goto no_room;
610 }
611 }
612 break;
613 case EVENT_TYPE_LONG:
614 /* 64-bit signed long */
615 {
Jeff Brown44193d92015-04-28 12:47:02 -0700616 uint64_t lval;
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -0700617
618 if (eventDataLen < 8)
619 return -1;
Mark Salyzyn8470dad2015-03-06 20:42:57 +0000620 lval = get8LE(eventData);
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -0700621 eventData += 8;
622 eventDataLen -= 8;
623
Jeff Brown44193d92015-04-28 12:47:02 -0700624 outCount = snprintf(outBuf, outBufLen, "%" PRId64, lval);
625 if (outCount < outBufLen) {
626 outBuf += outCount;
627 outBufLen -= outCount;
628 } else {
629 /* halt output */
630 goto no_room;
631 }
632 }
633 break;
634 case EVENT_TYPE_FLOAT:
635 /* float */
636 {
637 uint32_t ival;
638 float fval;
639
640 if (eventDataLen < 4)
641 return -1;
642 ival = get4LE(eventData);
643 fval = *(float*)&ival;
644 eventData += 4;
645 eventDataLen -= 4;
646
647 outCount = snprintf(outBuf, outBufLen, "%f", fval);
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -0700648 if (outCount < outBufLen) {
649 outBuf += outCount;
650 outBufLen -= outCount;
651 } else {
652 /* halt output */
653 goto no_room;
654 }
655 }
656 break;
657 case EVENT_TYPE_STRING:
658 /* UTF-8 chars, not NULL-terminated */
659 {
660 unsigned int strLen;
661
662 if (eventDataLen < 4)
663 return -1;
Mark Salyzyn8470dad2015-03-06 20:42:57 +0000664 strLen = get4LE(eventData);
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -0700665 eventData += 4;
666 eventDataLen -= 4;
667
668 if (eventDataLen < strLen)
669 return -1;
670
671 if (strLen < outBufLen) {
672 memcpy(outBuf, eventData, strLen);
673 outBuf += strLen;
674 outBufLen -= strLen;
675 } else if (outBufLen > 0) {
676 /* copy what we can */
677 memcpy(outBuf, eventData, outBufLen);
678 outBuf += outBufLen;
679 outBufLen -= outBufLen;
680 goto no_room;
681 }
682 eventData += strLen;
683 eventDataLen -= strLen;
684 break;
685 }
686 case EVENT_TYPE_LIST:
687 /* N items, all different types */
688 {
689 unsigned char count;
690 int i;
691
692 if (eventDataLen < 1)
693 return -1;
694
695 count = *eventData++;
696 eventDataLen--;
697
698 if (outBufLen > 0) {
699 *outBuf++ = '[';
700 outBufLen--;
701 } else {
702 goto no_room;
703 }
704
705 for (i = 0; i < count; i++) {
706 result = android_log_printBinaryEvent(&eventData, &eventDataLen,
707 &outBuf, &outBufLen);
708 if (result != 0)
709 goto bail;
710
711 if (i < count-1) {
712 if (outBufLen > 0) {
713 *outBuf++ = ',';
714 outBufLen--;
715 } else {
716 goto no_room;
717 }
718 }
719 }
720
721 if (outBufLen > 0) {
722 *outBuf++ = ']';
723 outBufLen--;
724 } else {
725 goto no_room;
726 }
727 }
728 break;
729 default:
730 fprintf(stderr, "Unknown binary event type %d\n", type);
731 return -1;
732 }
733
734bail:
735 *pEventData = eventData;
736 *pEventDataLen = eventDataLen;
737 *pOutBuf = outBuf;
738 *pOutBufLen = outBufLen;
739 return result;
740
741no_room:
742 result = 1;
743 goto bail;
744}
745
746/**
747 * Convert a binary log entry to ASCII form.
748 *
749 * For convenience we mimic the processLogBuffer API. There is no
750 * pre-defined output length for the binary data, since we're free to format
751 * it however we choose, which means we can't really use a fixed-size buffer
752 * here.
753 */
Mark Salyzynbe1d3c22016-03-10 08:25:33 -0800754LIBLOG_ABI_PUBLIC int android_log_processBinaryLogBuffer(
755 struct logger_entry *buf,
756 AndroidLogEntry *entry,
757 const EventTagMap *map,
758 char *messageBuf, int messageBufLen)
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -0700759{
760 size_t inCount;
761 unsigned int tagIndex;
762 const unsigned char* eventData;
763
764 entry->tv_sec = buf->sec;
765 entry->tv_nsec = buf->nsec;
766 entry->priority = ANDROID_LOG_INFO;
Mark Salyzyn90e7af32015-12-07 16:52:42 -0800767 entry->uid = -1;
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -0700768 entry->pid = buf->pid;
769 entry->tid = buf->tid;
770
771 /*
Mark Salyzyn7bc80232015-12-11 12:32:53 -0800772 * Pull the tag out, fill in some additional details based on incoming
773 * buffer version (v3 adds lid, v4 adds uid).
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -0700774 */
775 eventData = (const unsigned char*) buf->msg;
Mark Salyzyn40b21552013-12-18 12:59:01 -0800776 struct logger_entry_v2 *buf2 = (struct logger_entry_v2 *)buf;
777 if (buf2->hdr_size) {
778 eventData = ((unsigned char *)buf2) + buf2->hdr_size;
Mark Salyzyn7bc80232015-12-11 12:32:53 -0800779 if ((buf2->hdr_size >= sizeof(struct logger_entry_v3)) &&
780 (((struct logger_entry_v3 *)buf)->lid == LOG_ID_SECURITY)) {
781 entry->priority = ANDROID_LOG_WARN;
782 }
Mark Salyzyn90e7af32015-12-07 16:52:42 -0800783 if (buf2->hdr_size >= sizeof(struct logger_entry_v4)) {
784 entry->uid = ((struct logger_entry_v4 *)buf)->uid;
785 }
Mark Salyzyn40b21552013-12-18 12:59:01 -0800786 }
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -0700787 inCount = buf->len;
788 if (inCount < 4)
789 return -1;
Mark Salyzyn8470dad2015-03-06 20:42:57 +0000790 tagIndex = get4LE(eventData);
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -0700791 eventData += 4;
792 inCount -= 4;
793
794 if (map != NULL) {
795 entry->tag = android_lookupEventTag(map, tagIndex);
796 } else {
797 entry->tag = NULL;
798 }
799
800 /*
801 * If we don't have a map, or didn't find the tag number in the map,
802 * stuff a generated tag value into the start of the output buffer and
803 * shift the buffer pointers down.
804 */
805 if (entry->tag == NULL) {
806 int tagLen;
807
808 tagLen = snprintf(messageBuf, messageBufLen, "[%d]", tagIndex);
809 entry->tag = messageBuf;
810 messageBuf += tagLen+1;
811 messageBufLen -= tagLen+1;
812 }
813
814 /*
815 * Format the event log data into the buffer.
816 */
817 char* outBuf = messageBuf;
818 size_t outRemaining = messageBufLen-1; /* leave one for nul byte */
819 int result;
820 result = android_log_printBinaryEvent(&eventData, &inCount, &outBuf,
821 &outRemaining);
822 if (result < 0) {
823 fprintf(stderr, "Binary log entry conversion failed\n");
824 return -1;
825 } else if (result == 1) {
826 if (outBuf > messageBuf) {
827 /* leave an indicator */
828 *(outBuf-1) = '!';
829 } else {
830 /* no room to output anything at all */
831 *outBuf++ = '!';
832 outRemaining--;
833 }
834 /* pretend we ate all the data */
835 inCount = 0;
836 }
837
838 /* eat the silly terminating '\n' */
839 if (inCount == 1 && *eventData == '\n') {
840 eventData++;
841 inCount--;
842 }
843
844 if (inCount != 0) {
845 fprintf(stderr,
Andrew Hsiehd2c8f522012-02-27 16:48:18 -0800846 "Warning: leftover binary log data (%zu bytes)\n", inCount);
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -0700847 }
848
849 /*
850 * Terminate the buffer. The NUL byte does not count as part of
851 * entry->messageLen.
852 */
853 *outBuf = '\0';
854 entry->messageLen = outBuf - messageBuf;
855 assert(entry->messageLen == (messageBufLen-1) - outRemaining);
856
857 entry->message = messageBuf;
858
859 return 0;
860}
861
Mark Salyzynb932b2f2015-05-15 09:01:58 -0700862/*
863 * One utf8 character at a time
864 *
865 * Returns the length of the utf8 character in the buffer,
866 * or -1 if illegal or truncated
867 *
868 * Open coded from libutils/Unicode.cpp, borrowed from utf8_length(),
869 * can not remove from here because of library circular dependencies.
870 * Expect one-day utf8_character_length with the same signature could
871 * _also_ be part of libutils/Unicode.cpp if its usefullness needs to
872 * propagate globally.
873 */
Mark Salyzynbe1d3c22016-03-10 08:25:33 -0800874LIBLOG_WEAK ssize_t utf8_character_length(const char *src, size_t len)
Mark Salyzynb932b2f2015-05-15 09:01:58 -0700875{
876 const char *cur = src;
877 const char first_char = *cur++;
878 static const uint32_t kUnicodeMaxCodepoint = 0x0010FFFF;
879 int32_t mask, to_ignore_mask;
880 size_t num_to_read;
881 uint32_t utf32;
882
883 if ((first_char & 0x80) == 0) { /* ASCII */
Mark Salyzynfaa92e92015-09-08 07:57:27 -0700884 return first_char ? 1 : -1;
Mark Salyzynb932b2f2015-05-15 09:01:58 -0700885 }
886
887 /*
888 * (UTF-8's character must not be like 10xxxxxx,
889 * but 110xxxxx, 1110xxxx, ... or 1111110x)
890 */
891 if ((first_char & 0x40) == 0) {
892 return -1;
893 }
894
895 for (utf32 = 1, num_to_read = 1, mask = 0x40, to_ignore_mask = 0x80;
896 num_to_read < 5 && (first_char & mask);
897 num_to_read++, to_ignore_mask |= mask, mask >>= 1) {
898 if (num_to_read > len) {
899 return -1;
900 }
901 if ((*cur & 0xC0) != 0x80) { /* can not be 10xxxxxx? */
902 return -1;
903 }
904 utf32 = (utf32 << 6) + (*cur++ & 0b00111111);
905 }
906 /* "first_char" must be (110xxxxx - 11110xxx) */
907 if (num_to_read >= 5) {
908 return -1;
909 }
910 to_ignore_mask |= mask;
911 utf32 |= ((~to_ignore_mask) & first_char) << (6 * (num_to_read - 1));
912 if (utf32 > kUnicodeMaxCodepoint) {
913 return -1;
914 }
915 return num_to_read;
916}
917
918/*
919 * Convert to printable from message to p buffer, return string length. If p is
920 * NULL, do not copy, but still return the expected string length.
921 */
922static size_t convertPrintable(char *p, const char *message, size_t messageLen)
923{
924 char *begin = p;
925 bool print = p != NULL;
926
927 while (messageLen) {
928 char buf[6];
929 ssize_t len = sizeof(buf) - 1;
930 if ((size_t)len > messageLen) {
931 len = messageLen;
932 }
933 len = utf8_character_length(message, len);
934
935 if (len < 0) {
936 snprintf(buf, sizeof(buf),
937 ((messageLen > 1) && isdigit(message[1]))
938 ? "\\%03o"
939 : "\\%o",
940 *message & 0377);
941 len = 1;
942 } else {
943 buf[0] = '\0';
944 if (len == 1) {
945 if (*message == '\a') {
946 strcpy(buf, "\\a");
947 } else if (*message == '\b') {
948 strcpy(buf, "\\b");
949 } else if (*message == '\t') {
Mark Salyzyn65d5ca22015-11-18 09:58:00 -0800950 strcpy(buf, "\t"); // Do not escape tabs
Mark Salyzynb932b2f2015-05-15 09:01:58 -0700951 } else if (*message == '\v') {
952 strcpy(buf, "\\v");
953 } else if (*message == '\f') {
954 strcpy(buf, "\\f");
955 } else if (*message == '\r') {
956 strcpy(buf, "\\r");
957 } else if (*message == '\\') {
958 strcpy(buf, "\\\\");
959 } else if ((*message < ' ') || (*message & 0x80)) {
960 snprintf(buf, sizeof(buf), "\\%o", *message & 0377);
961 }
962 }
963 if (!buf[0]) {
964 strncpy(buf, message, len);
965 buf[len] = '\0';
966 }
967 }
968 if (print) {
969 strcpy(p, buf);
970 }
971 p += strlen(buf);
972 message += len;
973 messageLen -= len;
974 }
975 return p - begin;
976}
977
Mark Salyzynbe1d3c22016-03-10 08:25:33 -0800978static char *readSeconds(char *e, struct timespec *t)
Mark Salyzyn4cbed022015-08-31 15:53:41 -0700979{
980 unsigned long multiplier;
981 char *p;
982 t->tv_sec = strtoul(e, &p, 10);
983 if (*p != '.') {
984 return NULL;
985 }
986 t->tv_nsec = 0;
987 multiplier = NS_PER_SEC;
988 while (isdigit(*++p) && (multiplier /= 10)) {
989 t->tv_nsec += (*p - '0') * multiplier;
990 }
991 return p;
992}
993
994static struct timespec *sumTimespec(struct timespec *left,
995 struct timespec *right)
996{
997 left->tv_nsec += right->tv_nsec;
998 left->tv_sec += right->tv_sec;
999 if (left->tv_nsec >= (long)NS_PER_SEC) {
1000 left->tv_nsec -= NS_PER_SEC;
1001 left->tv_sec += 1;
1002 }
1003 return left;
1004}
1005
1006static struct timespec *subTimespec(struct timespec *result,
1007 struct timespec *left,
1008 struct timespec *right)
1009{
1010 result->tv_nsec = left->tv_nsec - right->tv_nsec;
1011 result->tv_sec = left->tv_sec - right->tv_sec;
1012 if (result->tv_nsec < 0) {
1013 result->tv_nsec += NS_PER_SEC;
1014 result->tv_sec -= 1;
1015 }
1016 return result;
1017}
1018
1019static long long nsecTimespec(struct timespec *now)
1020{
1021 return (long long)now->tv_sec * NS_PER_SEC + now->tv_nsec;
1022}
1023
1024static void convertMonotonic(struct timespec *result,
1025 const AndroidLogEntry *entry)
1026{
1027 struct listnode *node;
1028 struct conversionList {
1029 struct listnode node; /* first */
1030 struct timespec time;
1031 struct timespec convert;
1032 } *list, *next;
1033 struct timespec time, convert;
1034
1035 /* If we do not have a conversion list, build one up */
1036 if (list_empty(&convertHead)) {
1037 bool suspended_pending = false;
1038 struct timespec suspended_monotonic = { 0, 0 };
1039 struct timespec suspended_diff = { 0, 0 };
1040
1041 /*
1042 * Read dmesg for _some_ synchronization markers and insert
1043 * Anything in the Android Logger before the dmesg logging span will
1044 * be highly suspect regarding the monotonic time calculations.
1045 */
Mark Salyzyn78786da2016-04-28 16:06:24 -07001046 FILE *p = popen("/system/bin/dmesg", "re");
Mark Salyzyn4cbed022015-08-31 15:53:41 -07001047 if (p) {
1048 char *line = NULL;
1049 size_t len = 0;
1050 while (getline(&line, &len, p) > 0) {
1051 static const char suspend[] = "PM: suspend entry ";
1052 static const char resume[] = "PM: suspend exit ";
1053 static const char healthd[] = "healthd";
1054 static const char battery[] = ": battery ";
1055 static const char suspended[] = "Suspended for ";
1056 struct timespec monotonic;
1057 struct tm tm;
1058 char *cp, *e = line;
1059 bool add_entry = true;
1060
1061 if (*e == '<') {
1062 while (*e && (*e != '>')) {
1063 ++e;
1064 }
1065 if (*e != '>') {
1066 continue;
1067 }
1068 }
1069 if (*e != '[') {
1070 continue;
1071 }
1072 while (*++e == ' ') {
1073 ;
1074 }
1075 e = readSeconds(e, &monotonic);
1076 if (!e || (*e != ']')) {
1077 continue;
1078 }
1079
1080 if ((e = strstr(e, suspend))) {
1081 e += sizeof(suspend) - 1;
1082 } else if ((e = strstr(line, resume))) {
1083 e += sizeof(resume) - 1;
1084 } else if (((e = strstr(line, healthd)))
1085 && ((e = strstr(e + sizeof(healthd) - 1, battery)))) {
1086 /* NB: healthd is roughly 150us late, worth the price to
1087 * deal with ntp-induced or hardware clock drift. */
1088 e += sizeof(battery) - 1;
1089 } else if ((e = strstr(line, suspended))) {
1090 e += sizeof(suspended) - 1;
1091 e = readSeconds(e, &time);
1092 if (!e) {
1093 continue;
1094 }
1095 add_entry = false;
1096 suspended_pending = true;
1097 suspended_monotonic = monotonic;
1098 suspended_diff = time;
1099 } else {
1100 continue;
1101 }
1102 if (add_entry) {
1103 /* look for "????-??-?? ??:??:??.????????? UTC" */
1104 cp = strstr(e, " UTC");
1105 if (!cp || ((cp - e) < 29) || (cp[-10] != '.')) {
1106 continue;
1107 }
1108 e = cp - 29;
1109 cp = readSeconds(cp - 10, &time);
1110 if (!cp) {
1111 continue;
1112 }
1113 cp = strptime(e, "%Y-%m-%d %H:%M:%S.", &tm);
1114 if (!cp) {
1115 continue;
1116 }
1117 cp = getenv(tz);
1118 if (cp) {
1119 cp = strdup(cp);
1120 }
1121 setenv(tz, utc, 1);
1122 time.tv_sec = mktime(&tm);
1123 if (cp) {
1124 setenv(tz, cp, 1);
1125 free(cp);
1126 } else {
1127 unsetenv(tz);
1128 }
1129 list = calloc(1, sizeof(struct conversionList));
1130 list_init(&list->node);
1131 list->time = time;
1132 subTimespec(&list->convert, &time, &monotonic);
1133 list_add_tail(&convertHead, &list->node);
1134 }
1135 if (suspended_pending && !list_empty(&convertHead)) {
1136 list = node_to_item(list_tail(&convertHead),
1137 struct conversionList, node);
1138 if (subTimespec(&time,
1139 subTimespec(&time,
1140 &list->time,
1141 &list->convert),
1142 &suspended_monotonic)->tv_sec > 0) {
1143 /* resume, what is convert factor before? */
1144 subTimespec(&convert, &list->convert, &suspended_diff);
1145 } else {
1146 /* suspend */
1147 convert = list->convert;
1148 }
1149 time = suspended_monotonic;
1150 sumTimespec(&time, &convert);
1151 /* breakpoint just before sleep */
1152 list = calloc(1, sizeof(struct conversionList));
1153 list_init(&list->node);
1154 list->time = time;
1155 list->convert = convert;
1156 list_add_tail(&convertHead, &list->node);
1157 /* breakpoint just after sleep */
1158 list = calloc(1, sizeof(struct conversionList));
1159 list_init(&list->node);
1160 list->time = time;
1161 sumTimespec(&list->time, &suspended_diff);
1162 list->convert = convert;
1163 sumTimespec(&list->convert, &suspended_diff);
1164 list_add_tail(&convertHead, &list->node);
1165 suspended_pending = false;
1166 }
1167 }
1168 pclose(p);
1169 }
1170 /* last entry is our current time conversion */
1171 list = calloc(1, sizeof(struct conversionList));
1172 list_init(&list->node);
1173 clock_gettime(CLOCK_REALTIME, &list->time);
1174 clock_gettime(CLOCK_MONOTONIC, &convert);
1175 clock_gettime(CLOCK_MONOTONIC, &time);
1176 /* Correct for instant clock_gettime latency (syscall or ~30ns) */
1177 subTimespec(&time, &convert, subTimespec(&time, &time, &convert));
1178 /* Calculate conversion factor */
1179 subTimespec(&list->convert, &list->time, &time);
1180 list_add_tail(&convertHead, &list->node);
1181 if (suspended_pending) {
1182 /* manufacture a suspend @ point before */
1183 subTimespec(&convert, &list->convert, &suspended_diff);
1184 time = suspended_monotonic;
1185 sumTimespec(&time, &convert);
1186 /* breakpoint just after sleep */
1187 list = calloc(1, sizeof(struct conversionList));
1188 list_init(&list->node);
1189 list->time = time;
1190 sumTimespec(&list->time, &suspended_diff);
1191 list->convert = convert;
1192 sumTimespec(&list->convert, &suspended_diff);
1193 list_add_head(&convertHead, &list->node);
1194 /* breakpoint just before sleep */
1195 list = calloc(1, sizeof(struct conversionList));
1196 list_init(&list->node);
1197 list->time = time;
1198 list->convert = convert;
1199 list_add_head(&convertHead, &list->node);
1200 }
1201 }
1202
1203 /* Find the breakpoint in the conversion list */
1204 list = node_to_item(list_head(&convertHead), struct conversionList, node);
1205 next = NULL;
1206 list_for_each(node, &convertHead) {
1207 next = node_to_item(node, struct conversionList, node);
1208 if (entry->tv_sec < next->time.tv_sec) {
1209 break;
1210 } else if (entry->tv_sec == next->time.tv_sec) {
1211 if (entry->tv_nsec < next->time.tv_nsec) {
1212 break;
1213 }
1214 }
1215 list = next;
1216 }
1217
1218 /* blend time from one breakpoint to the next */
1219 convert = list->convert;
1220 if (next) {
1221 unsigned long long total, run;
1222
1223 total = nsecTimespec(subTimespec(&time, &next->time, &list->time));
1224 time.tv_sec = entry->tv_sec;
1225 time.tv_nsec = entry->tv_nsec;
1226 run = nsecTimespec(subTimespec(&time, &time, &list->time));
1227 if (run < total) {
1228 long long crun;
1229
1230 float f = nsecTimespec(subTimespec(&time, &next->convert, &convert));
1231 f *= run;
1232 f /= total;
1233 crun = f;
1234 convert.tv_sec += crun / (long long)NS_PER_SEC;
1235 if (crun < 0) {
1236 convert.tv_nsec -= (-crun) % NS_PER_SEC;
1237 if (convert.tv_nsec < 0) {
1238 convert.tv_nsec += NS_PER_SEC;
1239 convert.tv_sec -= 1;
1240 }
1241 } else {
1242 convert.tv_nsec += crun % NS_PER_SEC;
1243 if (convert.tv_nsec >= (long)NS_PER_SEC) {
1244 convert.tv_nsec -= NS_PER_SEC;
1245 convert.tv_sec += 1;
1246 }
1247 }
1248 }
1249 }
1250
1251 /* Apply the correction factor */
1252 result->tv_sec = entry->tv_sec;
1253 result->tv_nsec = entry->tv_nsec;
1254 subTimespec(result, result, &convert);
1255}
1256
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -07001257/**
1258 * Formats a log message into a buffer
1259 *
1260 * Uses defaultBuffer if it can, otherwise malloc()'s a new buffer
1261 * If return value != defaultBuffer, caller must call free()
1262 * Returns NULL on malloc error
1263 */
1264
Mark Salyzynbe1d3c22016-03-10 08:25:33 -08001265LIBLOG_ABI_PUBLIC char *android_log_formatLogLine (
1266 AndroidLogFormat *p_format,
1267 char *defaultBuffer,
1268 size_t defaultBufferSize,
1269 const AndroidLogEntry *entry,
1270 size_t *p_outLength)
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -07001271{
Yabin Cui8a985352014-11-13 10:02:08 -08001272#if !defined(_WIN32)
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -07001273 struct tm tmBuf;
1274#endif
1275 struct tm* ptm;
Mark Salyzynf28f6a92015-08-31 08:01:33 -07001276 char timeBuf[64]; /* good margin, 23+nul for msec, 26+nul for usec */
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -07001277 char prefixBuf[128], suffixBuf[128];
1278 char priChar;
1279 int prefixSuffixIsHeaderFooter = 0;
Mark Salyzyn90e7af32015-12-07 16:52:42 -08001280 char *ret;
Mark Salyzyn4cbed022015-08-31 15:53:41 -07001281 time_t now;
1282 unsigned long nsec;
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -07001283
1284 priChar = filterPriToChar(entry->priority);
Pierre Zurekead88fc2010-10-17 22:39:37 +02001285 size_t prefixLen = 0, suffixLen = 0;
1286 size_t len;
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -07001287
1288 /*
1289 * Get the current date/time in pretty form
1290 *
1291 * It's often useful when examining a log with "less" to jump to
1292 * a specific point in the file by searching for the date/time stamp.
1293 * For this reason it's very annoying to have regexp meta characters
1294 * in the time stamp. Don't use forward slashes, parenthesis,
1295 * brackets, asterisks, or other special chars here.
Mark Salyzynf28f6a92015-08-31 08:01:33 -07001296 *
1297 * The caller may have affected the timezone environment, this is
1298 * expected to be sensitive to that.
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -07001299 */
Mark Salyzyn4cbed022015-08-31 15:53:41 -07001300 now = entry->tv_sec;
1301 nsec = entry->tv_nsec;
1302 if (p_format->monotonic_output) {
Mark Salyzynb6bee332015-09-08 08:56:32 -07001303 // prevent convertMonotonic from being called if logd is monotonic
Mark Salyzynba7a9a02015-12-01 15:57:25 -08001304 if (android_log_clockid() != CLOCK_MONOTONIC) {
Mark Salyzynb6bee332015-09-08 08:56:32 -07001305 struct timespec time;
1306 convertMonotonic(&time, entry);
1307 now = time.tv_sec;
1308 nsec = time.tv_nsec;
1309 }
Mark Salyzyn4cbed022015-08-31 15:53:41 -07001310 }
1311 if (now < 0) {
1312 nsec = NS_PER_SEC - nsec;
1313 }
1314 if (p_format->epoch_output || p_format->monotonic_output) {
1315 ptm = NULL;
1316 snprintf(timeBuf, sizeof(timeBuf),
1317 p_format->monotonic_output ? "%6lld" : "%19lld",
1318 (long long)now);
1319 } else {
Yabin Cui8a985352014-11-13 10:02:08 -08001320#if !defined(_WIN32)
Mark Salyzyn4cbed022015-08-31 15:53:41 -07001321 ptm = localtime_r(&now, &tmBuf);
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -07001322#else
Mark Salyzyn4cbed022015-08-31 15:53:41 -07001323 ptm = localtime(&now);
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -07001324#endif
Mark Salyzyn4cbed022015-08-31 15:53:41 -07001325 strftime(timeBuf, sizeof(timeBuf),
1326 &"%Y-%m-%d %H:%M:%S"[p_format->year_output ? 0 : 3],
1327 ptm);
1328 }
Mark Salyzyne1f20042015-05-06 08:40:40 -07001329 len = strlen(timeBuf);
1330 if (p_format->usec_time_output) {
Mark Salyzynf28f6a92015-08-31 08:01:33 -07001331 len += snprintf(timeBuf + len, sizeof(timeBuf) - len,
Mark Salyzyn4cbed022015-08-31 15:53:41 -07001332 ".%06ld", nsec / US_PER_NSEC);
Mark Salyzyne1f20042015-05-06 08:40:40 -07001333 } else {
Mark Salyzynf28f6a92015-08-31 08:01:33 -07001334 len += snprintf(timeBuf + len, sizeof(timeBuf) - len,
Mark Salyzyn4cbed022015-08-31 15:53:41 -07001335 ".%03ld", nsec / MS_PER_NSEC);
Mark Salyzynf28f6a92015-08-31 08:01:33 -07001336 }
Mark Salyzyn4cbed022015-08-31 15:53:41 -07001337 if (p_format->zone_output && ptm) {
Mark Salyzynf28f6a92015-08-31 08:01:33 -07001338 strftime(timeBuf + len, sizeof(timeBuf) - len, " %z", ptm);
Mark Salyzyne1f20042015-05-06 08:40:40 -07001339 }
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -07001340
1341 /*
1342 * Construct a buffer containing the log header and log message.
1343 */
Pierre Zurekead88fc2010-10-17 22:39:37 +02001344 if (p_format->colored_output) {
1345 prefixLen = snprintf(prefixBuf, sizeof(prefixBuf), "\x1B[38;5;%dm",
1346 colorFromPri(entry->priority));
1347 prefixLen = MIN(prefixLen, sizeof(prefixBuf));
1348 suffixLen = snprintf(suffixBuf, sizeof(suffixBuf), "\x1B[0m");
1349 suffixLen = MIN(suffixLen, sizeof(suffixBuf));
1350 }
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -07001351
Mark Salyzyn90e7af32015-12-07 16:52:42 -08001352 char uid[16];
1353 uid[0] = '\0';
1354 if (p_format->uid_output) {
1355 if (entry->uid >= 0) {
Mark Salyzyn2aa510e2015-12-08 09:15:06 -08001356
William Roberts8a5b9ca2016-04-08 12:13:17 -07001357 /*
1358 * This code is Android specific, bionic guarantees that
1359 * calls to non-reentrant getpwuid() are thread safe.
1360 */
1361#ifndef __BIONIC__
1362#warning "This code assumes that getpwuid is thread safe, only true with Bionic!"
1363#endif
1364 struct passwd* pwd = getpwuid(entry->uid);
1365 if (pwd && (strlen(pwd->pw_name) <= 5)) {
1366 snprintf(uid, sizeof(uid), "%5s:", pwd->pw_name);
Mark Salyzyn2aa510e2015-12-08 09:15:06 -08001367 } else {
1368 // Not worth parsing package list, names all longer than 5
1369 snprintf(uid, sizeof(uid), "%5d:", entry->uid);
1370 }
Mark Salyzyn90e7af32015-12-07 16:52:42 -08001371 } else {
1372 snprintf(uid, sizeof(uid), " ");
1373 }
1374 }
1375
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -07001376 switch (p_format->format) {
1377 case FORMAT_TAG:
Pierre Zurekead88fc2010-10-17 22:39:37 +02001378 len = snprintf(prefixBuf + prefixLen, sizeof(prefixBuf) - prefixLen,
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -07001379 "%c/%-8s: ", priChar, entry->tag);
Pierre Zurekead88fc2010-10-17 22:39:37 +02001380 strcpy(suffixBuf + suffixLen, "\n");
1381 ++suffixLen;
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -07001382 break;
1383 case FORMAT_PROCESS:
Pierre Zurekead88fc2010-10-17 22:39:37 +02001384 len = snprintf(suffixBuf + suffixLen, sizeof(suffixBuf) - suffixLen,
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -07001385 " (%s)\n", entry->tag);
Pierre Zurekead88fc2010-10-17 22:39:37 +02001386 suffixLen += MIN(len, sizeof(suffixBuf) - suffixLen);
1387 len = snprintf(prefixBuf + prefixLen, sizeof(prefixBuf) - prefixLen,
Mark Salyzyn90e7af32015-12-07 16:52:42 -08001388 "%c(%s%5d) ", priChar, uid, entry->pid);
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -07001389 break;
1390 case FORMAT_THREAD:
Pierre Zurekead88fc2010-10-17 22:39:37 +02001391 len = snprintf(prefixBuf + prefixLen, sizeof(prefixBuf) - prefixLen,
Mark Salyzyn90e7af32015-12-07 16:52:42 -08001392 "%c(%s%5d:%5d) ", priChar, uid, entry->pid, entry->tid);
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_RAW:
Pierre Zurekead88fc2010-10-17 22:39:37 +02001397 prefixBuf[prefixLen] = 0;
1398 len = 0;
1399 strcpy(suffixBuf + suffixLen, "\n");
1400 ++suffixLen;
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -07001401 break;
1402 case FORMAT_TIME:
Pierre Zurekead88fc2010-10-17 22:39:37 +02001403 len = snprintf(prefixBuf + prefixLen, sizeof(prefixBuf) - prefixLen,
Mark Salyzyn90e7af32015-12-07 16:52:42 -08001404 "%s %c/%-8s(%s%5d): ", timeBuf, priChar, entry->tag,
1405 uid, entry->pid);
Pierre Zurekead88fc2010-10-17 22:39:37 +02001406 strcpy(suffixBuf + suffixLen, "\n");
1407 ++suffixLen;
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -07001408 break;
1409 case FORMAT_THREADTIME:
Mark Salyzyn90e7af32015-12-07 16:52:42 -08001410 ret = strchr(uid, ':');
1411 if (ret) {
1412 *ret = ' ';
1413 }
Pierre Zurekead88fc2010-10-17 22:39:37 +02001414 len = snprintf(prefixBuf + prefixLen, sizeof(prefixBuf) - prefixLen,
Mark Salyzyn90e7af32015-12-07 16:52:42 -08001415 "%s %s%5d %5d %c %-8s: ", timeBuf,
1416 uid, entry->pid, entry->tid, priChar, entry->tag);
Pierre Zurekead88fc2010-10-17 22:39:37 +02001417 strcpy(suffixBuf + suffixLen, "\n");
1418 ++suffixLen;
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -07001419 break;
1420 case FORMAT_LONG:
Pierre Zurekead88fc2010-10-17 22:39:37 +02001421 len = snprintf(prefixBuf + prefixLen, sizeof(prefixBuf) - prefixLen,
Mark Salyzyn90e7af32015-12-07 16:52:42 -08001422 "[ %s %s%5d:%5d %c/%-8s ]\n",
1423 timeBuf, uid, entry->pid, entry->tid, priChar, entry->tag);
Pierre Zurekead88fc2010-10-17 22:39:37 +02001424 strcpy(suffixBuf + suffixLen, "\n\n");
1425 suffixLen += 2;
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -07001426 prefixSuffixIsHeaderFooter = 1;
1427 break;
1428 case FORMAT_BRIEF:
1429 default:
Pierre Zurekead88fc2010-10-17 22:39:37 +02001430 len = snprintf(prefixBuf + prefixLen, sizeof(prefixBuf) - prefixLen,
Mark Salyzyn90e7af32015-12-07 16:52:42 -08001431 "%c/%-8s(%s%5d): ", priChar, entry->tag, uid, entry->pid);
Pierre Zurekead88fc2010-10-17 22:39:37 +02001432 strcpy(suffixBuf + suffixLen, "\n");
1433 ++suffixLen;
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -07001434 break;
1435 }
Pierre Zurekead88fc2010-10-17 22:39:37 +02001436
Keith Prestonb45b5c92010-02-11 15:12:53 -06001437 /* snprintf has a weird return value. It returns what would have been
1438 * written given a large enough buffer. In the case that the prefix is
1439 * longer then our buffer(128), it messes up the calculations below
1440 * possibly causing heap corruption. To avoid this we double check and
1441 * set the length at the maximum (size minus null byte)
1442 */
Mark Salyzyn2f83d672016-03-11 12:06:12 -08001443 prefixLen += len;
1444 if (prefixLen >= sizeof(prefixBuf)) {
1445 prefixLen = sizeof(prefixBuf) - 1;
1446 prefixBuf[sizeof(prefixBuf) - 1] = '\0';
1447 }
1448 if (suffixLen >= sizeof(suffixBuf)) {
1449 suffixLen = sizeof(suffixBuf) - 1;
1450 suffixBuf[sizeof(suffixBuf) - 2] = '\n';
1451 suffixBuf[sizeof(suffixBuf) - 1] = '\0';
1452 }
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -07001453
1454 /* the following code is tragically unreadable */
1455
1456 size_t numLines;
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -07001457 char *p;
1458 size_t bufferSize;
1459 const char *pm;
1460
1461 if (prefixSuffixIsHeaderFooter) {
Mark Salyzynb932b2f2015-05-15 09:01:58 -07001462 /* we're just wrapping message with a header/footer */
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -07001463 numLines = 1;
1464 } else {
1465 pm = entry->message;
1466 numLines = 0;
1467
Mark Salyzynb932b2f2015-05-15 09:01:58 -07001468 /*
1469 * The line-end finding here must match the line-end finding
1470 * in for ( ... numLines...) loop below
1471 */
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -07001472 while (pm < (entry->message + entry->messageLen)) {
1473 if (*pm++ == '\n') numLines++;
1474 }
Mark Salyzynb932b2f2015-05-15 09:01:58 -07001475 /* plus one line for anything not newline-terminated at the end */
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -07001476 if (pm > entry->message && *(pm-1) != '\n') numLines++;
1477 }
1478
Mark Salyzynb932b2f2015-05-15 09:01:58 -07001479 /*
1480 * this is an upper bound--newlines in message may be counted
1481 * extraneously
1482 */
1483 bufferSize = (numLines * (prefixLen + suffixLen)) + 1;
1484 if (p_format->printable_output) {
1485 /* Calculate extra length to convert non-printable to printable */
1486 bufferSize += convertPrintable(NULL, entry->message, entry->messageLen);
1487 } else {
1488 bufferSize += entry->messageLen;
1489 }
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -07001490
1491 if (defaultBufferSize >= bufferSize) {
1492 ret = defaultBuffer;
1493 } else {
1494 ret = (char *)malloc(bufferSize);
1495
1496 if (ret == NULL) {
1497 return ret;
1498 }
1499 }
1500
1501 ret[0] = '\0'; /* to start strcat off */
1502
1503 p = ret;
1504 pm = entry->message;
1505
1506 if (prefixSuffixIsHeaderFooter) {
1507 strcat(p, prefixBuf);
1508 p += prefixLen;
Mark Salyzynb932b2f2015-05-15 09:01:58 -07001509 if (p_format->printable_output) {
1510 p += convertPrintable(p, entry->message, entry->messageLen);
1511 } else {
1512 strncat(p, entry->message, entry->messageLen);
1513 p += entry->messageLen;
1514 }
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -07001515 strcat(p, suffixBuf);
1516 p += suffixLen;
1517 } else {
Mark Salyzyn7cc80132016-01-20 13:52:46 -08001518 do {
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -07001519 const char *lineStart;
1520 size_t lineLen;
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -07001521 lineStart = pm;
1522
Mark Salyzynb932b2f2015-05-15 09:01:58 -07001523 /* Find the next end-of-line in message */
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -07001524 while (pm < (entry->message + entry->messageLen)
1525 && *pm != '\n') pm++;
1526 lineLen = pm - lineStart;
1527
1528 strcat(p, prefixBuf);
1529 p += prefixLen;
Mark Salyzynb932b2f2015-05-15 09:01:58 -07001530 if (p_format->printable_output) {
1531 p += convertPrintable(p, lineStart, lineLen);
1532 } else {
1533 strncat(p, lineStart, lineLen);
1534 p += lineLen;
1535 }
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -07001536 strcat(p, suffixBuf);
1537 p += suffixLen;
1538
1539 if (*pm == '\n') pm++;
Mark Salyzyn7cc80132016-01-20 13:52:46 -08001540 } while (pm < (entry->message + entry->messageLen));
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -07001541 }
1542
1543 if (p_outLength != NULL) {
1544 *p_outLength = p - ret;
1545 }
1546
1547 return ret;
1548}
1549
1550/**
1551 * Either print or do not print log line, based on filter
1552 *
1553 * Returns count bytes written
1554 */
1555
Mark Salyzynbe1d3c22016-03-10 08:25:33 -08001556LIBLOG_ABI_PUBLIC int android_log_printLogLine(
1557 AndroidLogFormat *p_format,
1558 int fd,
1559 const AndroidLogEntry *entry)
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -07001560{
1561 int ret;
1562 char defaultBuffer[512];
1563 char *outBuffer = NULL;
1564 size_t totalLen;
1565
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -07001566 outBuffer = android_log_formatLogLine(p_format, defaultBuffer,
1567 sizeof(defaultBuffer), entry, &totalLen);
1568
1569 if (!outBuffer)
1570 return -1;
1571
1572 do {
1573 ret = write(fd, outBuffer, totalLen);
1574 } while (ret < 0 && errno == EINTR);
1575
1576 if (ret < 0) {
1577 fprintf(stderr, "+++ LOG: write failed (errno=%d)\n", errno);
1578 ret = 0;
1579 goto done;
1580 }
1581
1582 if (((size_t)ret) < totalLen) {
1583 fprintf(stderr, "+++ LOG: write partial (%d of %d)\n", ret,
1584 (int)totalLen);
1585 goto done;
1586 }
1587
1588done:
1589 if (outBuffer != defaultBuffer) {
1590 free(outBuffer);
1591 }
1592
1593 return ret;
1594}