blob: 18af9dec077e4cf45682dcd81b091cef25a64cce [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>
Mark Salyzyn4fd05072016-10-18 11:30:11 -070024#include <inttypes.h>
William Roberts8a5b9ca2016-04-08 12:13:17 -070025#include <pwd.h>
Pierre Zurekead88fc2010-10-17 22:39:37 +020026#include <stdbool.h>
Mark Salyzyna04464a2014-04-30 08:50:53 -070027#include <stdint.h>
28#include <stdio.h>
29#include <stdlib.h>
30#include <string.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>
Mark Salyzynaeaaf812016-09-30 13:30:33 -070035#include <log/log.h>
Colin Cross9227bd32013-07-23 16:59:20 -070036#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 Salyzyn9b4d7e12017-01-30 09:16:09 -080055 bool nsec_time_output;
Mark Salyzynb932b2f2015-05-15 09:01:58 -070056 bool printable_output;
Mark Salyzynf28f6a92015-08-31 08:01:33 -070057 bool year_output;
58 bool zone_output;
Mark Salyzyn4cbed022015-08-31 15:53:41 -070059 bool epoch_output;
60 bool monotonic_output;
Mark Salyzyn90e7af32015-12-07 16:52:42 -080061 bool uid_output;
Mark Salyzyn4fd05072016-10-18 11:30:11 -070062 bool descriptive_output;
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -070063};
64
Pierre Zurekead88fc2010-10-17 22:39:37 +020065/*
Mark Salyzyn4fd05072016-10-18 11:30:11 -070066 * API issues prevent us from exposing "descriptive" in AndroidLogFormat_t
67 * during android_log_processBinaryLogBuffer(), so we break layering.
68 */
69static bool descriptive_output = false;
70
71/*
Pierre Zurekead88fc2010-10-17 22:39:37 +020072 * gnome-terminal color tags
73 * See http://misc.flogisoft.com/bash/tip_colors_and_formatting
74 * for ideas on how to set the forground color of the text for xterm.
75 * The color manipulation character stream is defined as:
76 * ESC [ 3 8 ; 5 ; <color#> m
77 */
78#define ANDROID_COLOR_BLUE 75
79#define ANDROID_COLOR_DEFAULT 231
80#define ANDROID_COLOR_GREEN 40
81#define ANDROID_COLOR_ORANGE 166
82#define ANDROID_COLOR_RED 196
83#define ANDROID_COLOR_YELLOW 226
84
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -070085static FilterInfo * filterinfo_new(const char * tag, android_LogPriority pri)
86{
87 FilterInfo *p_ret;
88
89 p_ret = (FilterInfo *)calloc(1, sizeof(FilterInfo));
90 p_ret->mTag = strdup(tag);
91 p_ret->mPri = pri;
92
93 return p_ret;
94}
95
Mark Salyzyna04464a2014-04-30 08:50:53 -070096/* balance to above, filterinfo_free left unimplemented */
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -070097
98/*
99 * Note: also accepts 0-9 priorities
100 * returns ANDROID_LOG_UNKNOWN if the character is unrecognized
101 */
102static android_LogPriority filterCharToPri (char c)
103{
104 android_LogPriority pri;
105
106 c = tolower(c);
107
108 if (c >= '0' && c <= '9') {
109 if (c >= ('0'+ANDROID_LOG_SILENT)) {
110 pri = ANDROID_LOG_VERBOSE;
111 } else {
112 pri = (android_LogPriority)(c - '0');
113 }
114 } else if (c == 'v') {
115 pri = ANDROID_LOG_VERBOSE;
116 } else if (c == 'd') {
117 pri = ANDROID_LOG_DEBUG;
118 } else if (c == 'i') {
119 pri = ANDROID_LOG_INFO;
120 } else if (c == 'w') {
121 pri = ANDROID_LOG_WARN;
122 } else if (c == 'e') {
123 pri = ANDROID_LOG_ERROR;
124 } else if (c == 'f') {
125 pri = ANDROID_LOG_FATAL;
126 } else if (c == 's') {
127 pri = ANDROID_LOG_SILENT;
128 } else if (c == '*') {
129 pri = ANDROID_LOG_DEFAULT;
130 } else {
131 pri = ANDROID_LOG_UNKNOWN;
132 }
133
134 return pri;
135}
136
137static char filterPriToChar (android_LogPriority pri)
138{
139 switch (pri) {
140 case ANDROID_LOG_VERBOSE: return 'V';
141 case ANDROID_LOG_DEBUG: return 'D';
142 case ANDROID_LOG_INFO: return 'I';
143 case ANDROID_LOG_WARN: return 'W';
144 case ANDROID_LOG_ERROR: return 'E';
145 case ANDROID_LOG_FATAL: return 'F';
146 case ANDROID_LOG_SILENT: return 'S';
147
148 case ANDROID_LOG_DEFAULT:
149 case ANDROID_LOG_UNKNOWN:
150 default: return '?';
151 }
152}
153
Pierre Zurekead88fc2010-10-17 22:39:37 +0200154static int colorFromPri (android_LogPriority pri)
155{
156 switch (pri) {
157 case ANDROID_LOG_VERBOSE: return ANDROID_COLOR_DEFAULT;
158 case ANDROID_LOG_DEBUG: return ANDROID_COLOR_BLUE;
159 case ANDROID_LOG_INFO: return ANDROID_COLOR_GREEN;
160 case ANDROID_LOG_WARN: return ANDROID_COLOR_ORANGE;
161 case ANDROID_LOG_ERROR: return ANDROID_COLOR_RED;
162 case ANDROID_LOG_FATAL: return ANDROID_COLOR_RED;
163 case ANDROID_LOG_SILENT: return ANDROID_COLOR_DEFAULT;
164
165 case ANDROID_LOG_DEFAULT:
166 case ANDROID_LOG_UNKNOWN:
167 default: return ANDROID_COLOR_DEFAULT;
168 }
169}
170
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -0700171static android_LogPriority filterPriForTag(
172 AndroidLogFormat *p_format, const char *tag)
173{
174 FilterInfo *p_curFilter;
175
176 for (p_curFilter = p_format->filters
177 ; p_curFilter != NULL
178 ; p_curFilter = p_curFilter->p_next
179 ) {
180 if (0 == strcmp(tag, p_curFilter->mTag)) {
181 if (p_curFilter->mPri == ANDROID_LOG_DEFAULT) {
182 return p_format->global_pri;
183 } else {
184 return p_curFilter->mPri;
185 }
186 }
187 }
188
189 return p_format->global_pri;
190}
191
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -0700192/**
193 * returns 1 if this log line should be printed based on its priority
194 * and tag, and 0 if it should not
195 */
Mark Salyzynbe1d3c22016-03-10 08:25:33 -0800196LIBLOG_ABI_PUBLIC int android_log_shouldPrintLine (
197 AndroidLogFormat *p_format,
198 const char *tag,
199 android_LogPriority pri)
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -0700200{
201 return pri >= filterPriForTag(p_format, tag);
202}
203
Mark Salyzynbe1d3c22016-03-10 08:25:33 -0800204LIBLOG_ABI_PUBLIC AndroidLogFormat *android_log_format_new()
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -0700205{
206 AndroidLogFormat *p_ret;
207
208 p_ret = calloc(1, sizeof(AndroidLogFormat));
209
210 p_ret->global_pri = ANDROID_LOG_VERBOSE;
211 p_ret->format = FORMAT_BRIEF;
Pierre Zurekead88fc2010-10-17 22:39:37 +0200212 p_ret->colored_output = false;
Mark Salyzyne1f20042015-05-06 08:40:40 -0700213 p_ret->usec_time_output = false;
Mark Salyzyn9b4d7e12017-01-30 09:16:09 -0800214 p_ret->nsec_time_output = false;
Mark Salyzynb932b2f2015-05-15 09:01:58 -0700215 p_ret->printable_output = false;
Mark Salyzynf28f6a92015-08-31 08:01:33 -0700216 p_ret->year_output = false;
217 p_ret->zone_output = false;
Mark Salyzyn4cbed022015-08-31 15:53:41 -0700218 p_ret->epoch_output = false;
Mark Salyzynba7a9a02015-12-01 15:57:25 -0800219 p_ret->monotonic_output = android_log_clockid() == CLOCK_MONOTONIC;
Mark Salyzyn90e7af32015-12-07 16:52:42 -0800220 p_ret->uid_output = false;
Mark Salyzyn4fd05072016-10-18 11:30:11 -0700221 p_ret->descriptive_output = false;
222 descriptive_output = false;
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -0700223
224 return p_ret;
225}
226
Mark Salyzyn4cbed022015-08-31 15:53:41 -0700227static list_declare(convertHead);
228
Mark Salyzynbe1d3c22016-03-10 08:25:33 -0800229LIBLOG_ABI_PUBLIC void android_log_format_free(AndroidLogFormat *p_format)
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -0700230{
231 FilterInfo *p_info, *p_info_old;
232
233 p_info = p_format->filters;
234
235 while (p_info != NULL) {
236 p_info_old = p_info;
237 p_info = p_info->p_next;
238
239 free(p_info_old);
240 }
241
242 free(p_format);
Mark Salyzyn4cbed022015-08-31 15:53:41 -0700243
244 /* Free conversion resource, can always be reconstructed */
245 while (!list_empty(&convertHead)) {
246 struct listnode *node = list_head(&convertHead);
247 list_remove(node);
248 free(node);
249 }
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -0700250}
251
Mark Salyzynbe1d3c22016-03-10 08:25:33 -0800252LIBLOG_ABI_PUBLIC int android_log_setPrintFormat(
253 AndroidLogFormat *p_format,
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -0700254 AndroidLogPrintFormat format)
255{
Mark Salyzynb932b2f2015-05-15 09:01:58 -0700256 switch (format) {
257 case FORMAT_MODIFIER_COLOR:
Pierre Zurekead88fc2010-10-17 22:39:37 +0200258 p_format->colored_output = true;
Mark Salyzyne1f20042015-05-06 08:40:40 -0700259 return 0;
Mark Salyzynb932b2f2015-05-15 09:01:58 -0700260 case FORMAT_MODIFIER_TIME_USEC:
Mark Salyzyne1f20042015-05-06 08:40:40 -0700261 p_format->usec_time_output = true;
262 return 0;
Mark Salyzyn9b4d7e12017-01-30 09:16:09 -0800263 case FORMAT_MODIFIER_TIME_NSEC:
264 p_format->nsec_time_output = true;
265 return 0;
Mark Salyzynb932b2f2015-05-15 09:01:58 -0700266 case FORMAT_MODIFIER_PRINTABLE:
267 p_format->printable_output = true;
268 return 0;
Mark Salyzynf28f6a92015-08-31 08:01:33 -0700269 case FORMAT_MODIFIER_YEAR:
270 p_format->year_output = true;
271 return 0;
272 case FORMAT_MODIFIER_ZONE:
273 p_format->zone_output = !p_format->zone_output;
274 return 0;
Mark Salyzyn4cbed022015-08-31 15:53:41 -0700275 case FORMAT_MODIFIER_EPOCH:
276 p_format->epoch_output = true;
277 return 0;
278 case FORMAT_MODIFIER_MONOTONIC:
279 p_format->monotonic_output = true;
280 return 0;
Mark Salyzyn90e7af32015-12-07 16:52:42 -0800281 case FORMAT_MODIFIER_UID:
282 p_format->uid_output = true;
283 return 0;
Mark Salyzyn4fd05072016-10-18 11:30:11 -0700284 case FORMAT_MODIFIER_DESCRIPT:
285 p_format->descriptive_output = true;
286 descriptive_output = true;
287 return 0;
Mark Salyzynb932b2f2015-05-15 09:01:58 -0700288 default:
289 break;
Mark Salyzyne1f20042015-05-06 08:40:40 -0700290 }
291 p_format->format = format;
292 return 1;
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -0700293}
294
Mark Salyzynf28f6a92015-08-31 08:01:33 -0700295static const char tz[] = "TZ";
296static const char utc[] = "UTC";
297
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -0700298/**
299 * Returns FORMAT_OFF on invalid string
300 */
Mark Salyzynbe1d3c22016-03-10 08:25:33 -0800301LIBLOG_ABI_PUBLIC AndroidLogPrintFormat android_log_formatFromString(
302 const char * formatString)
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -0700303{
304 static AndroidLogPrintFormat format;
305
306 if (strcmp(formatString, "brief") == 0) format = FORMAT_BRIEF;
307 else if (strcmp(formatString, "process") == 0) format = FORMAT_PROCESS;
308 else if (strcmp(formatString, "tag") == 0) format = FORMAT_TAG;
309 else if (strcmp(formatString, "thread") == 0) format = FORMAT_THREAD;
310 else if (strcmp(formatString, "raw") == 0) format = FORMAT_RAW;
311 else if (strcmp(formatString, "time") == 0) format = FORMAT_TIME;
312 else if (strcmp(formatString, "threadtime") == 0) format = FORMAT_THREADTIME;
313 else if (strcmp(formatString, "long") == 0) format = FORMAT_LONG;
Mark Salyzyne1f20042015-05-06 08:40:40 -0700314 else if (strcmp(formatString, "color") == 0) format = FORMAT_MODIFIER_COLOR;
Mark Salyzyn4fd05072016-10-18 11:30:11 -0700315 else if (strcmp(formatString, "colour") == 0) format = FORMAT_MODIFIER_COLOR;
Mark Salyzyne1f20042015-05-06 08:40:40 -0700316 else if (strcmp(formatString, "usec") == 0) format = FORMAT_MODIFIER_TIME_USEC;
Mark Salyzyn9b4d7e12017-01-30 09:16:09 -0800317 else if (strcmp(formatString, "nsec") == 0) format = FORMAT_MODIFIER_TIME_NSEC;
Mark Salyzynb932b2f2015-05-15 09:01:58 -0700318 else if (strcmp(formatString, "printable") == 0) format = FORMAT_MODIFIER_PRINTABLE;
Mark Salyzynf28f6a92015-08-31 08:01:33 -0700319 else if (strcmp(formatString, "year") == 0) format = FORMAT_MODIFIER_YEAR;
320 else if (strcmp(formatString, "zone") == 0) format = FORMAT_MODIFIER_ZONE;
Mark Salyzyn4cbed022015-08-31 15:53:41 -0700321 else if (strcmp(formatString, "epoch") == 0) format = FORMAT_MODIFIER_EPOCH;
322 else if (strcmp(formatString, "monotonic") == 0) format = FORMAT_MODIFIER_MONOTONIC;
Mark Salyzyn90e7af32015-12-07 16:52:42 -0800323 else if (strcmp(formatString, "uid") == 0) format = FORMAT_MODIFIER_UID;
Mark Salyzyn4fd05072016-10-18 11:30:11 -0700324 else if (strcmp(formatString, "descriptive") == 0) format = FORMAT_MODIFIER_DESCRIPT;
Mark Salyzynf28f6a92015-08-31 08:01:33 -0700325 else {
326 extern char *tzname[2];
327 static const char gmt[] = "GMT";
328 char *cp = getenv(tz);
329 if (cp) {
330 cp = strdup(cp);
331 }
332 setenv(tz, formatString, 1);
333 /*
334 * Run tzset here to determine if the timezone is legitimate. If the
335 * zone is GMT, check if that is what was asked for, if not then
336 * did not match any on the system; report an error to caller.
337 */
338 tzset();
339 if (!tzname[0]
340 || ((!strcmp(tzname[0], utc)
341 || !strcmp(tzname[0], gmt)) /* error? */
342 && strcasecmp(formatString, utc)
343 && strcasecmp(formatString, gmt))) { /* ok */
344 if (cp) {
345 setenv(tz, cp, 1);
346 } else {
347 unsetenv(tz);
348 }
349 tzset();
350 format = FORMAT_OFF;
351 } else {
352 format = FORMAT_MODIFIER_ZONE;
353 }
354 free(cp);
355 }
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -0700356
357 return format;
358}
359
360/**
361 * filterExpression: a single filter expression
362 * eg "AT:d"
363 *
364 * returns 0 on success and -1 on invalid expression
365 *
366 * Assumes single threaded execution
367 */
368
Mark Salyzynbe1d3c22016-03-10 08:25:33 -0800369LIBLOG_ABI_PUBLIC int android_log_addFilterRule(
370 AndroidLogFormat *p_format,
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -0700371 const char *filterExpression)
372{
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -0700373 size_t tagNameLength;
374 android_LogPriority pri = ANDROID_LOG_DEFAULT;
375
376 tagNameLength = strcspn(filterExpression, ":");
377
378 if (tagNameLength == 0) {
379 goto error;
380 }
381
382 if(filterExpression[tagNameLength] == ':') {
383 pri = filterCharToPri(filterExpression[tagNameLength+1]);
384
385 if (pri == ANDROID_LOG_UNKNOWN) {
386 goto error;
387 }
388 }
389
390 if(0 == strncmp("*", filterExpression, tagNameLength)) {
Mark Salyzynb932b2f2015-05-15 09:01:58 -0700391 /*
392 * This filter expression refers to the global filter
393 * The default level for this is DEBUG if the priority
394 * is unspecified
395 */
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -0700396 if (pri == ANDROID_LOG_DEFAULT) {
397 pri = ANDROID_LOG_DEBUG;
398 }
399
400 p_format->global_pri = pri;
401 } else {
Mark Salyzynb932b2f2015-05-15 09:01:58 -0700402 /*
403 * for filter expressions that don't refer to the global
404 * filter, the default is verbose if the priority is unspecified
405 */
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -0700406 if (pri == ANDROID_LOG_DEFAULT) {
407 pri = ANDROID_LOG_VERBOSE;
408 }
409
410 char *tagName;
411
Mark Salyzynb932b2f2015-05-15 09:01:58 -0700412/*
413 * Presently HAVE_STRNDUP is never defined, so the second case is always taken
414 * Darwin doesn't have strnup, everything else does
415 */
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -0700416#ifdef HAVE_STRNDUP
417 tagName = strndup(filterExpression, tagNameLength);
418#else
Mark Salyzynb932b2f2015-05-15 09:01:58 -0700419 /* a few extra bytes copied... */
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -0700420 tagName = strdup(filterExpression);
421 tagName[tagNameLength] = '\0';
422#endif /*HAVE_STRNDUP*/
423
424 FilterInfo *p_fi = filterinfo_new(tagName, pri);
425 free(tagName);
426
427 p_fi->p_next = p_format->filters;
428 p_format->filters = p_fi;
429 }
430
431 return 0;
432error:
433 return -1;
434}
435
436
437/**
438 * filterString: a comma/whitespace-separated set of filter expressions
439 *
440 * eg "AT:d *:i"
441 *
442 * returns 0 on success and -1 on invalid expression
443 *
444 * Assumes single threaded execution
445 *
446 */
447
Mark Salyzynbe1d3c22016-03-10 08:25:33 -0800448LIBLOG_ABI_PUBLIC int android_log_addFilterString(
449 AndroidLogFormat *p_format,
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -0700450 const char *filterString)
451{
452 char *filterStringCopy = strdup (filterString);
453 char *p_cur = filterStringCopy;
454 char *p_ret;
455 int err;
456
Mark Salyzynb932b2f2015-05-15 09:01:58 -0700457 /* Yes, I'm using strsep */
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -0700458 while (NULL != (p_ret = strsep(&p_cur, " \t,"))) {
Mark Salyzynb932b2f2015-05-15 09:01:58 -0700459 /* ignore whitespace-only entries */
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -0700460 if(p_ret[0] != '\0') {
461 err = android_log_addFilterRule(p_format, p_ret);
462
463 if (err < 0) {
464 goto error;
465 }
466 }
467 }
468
469 free (filterStringCopy);
470 return 0;
471error:
472 free (filterStringCopy);
473 return -1;
474}
475
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -0700476/**
477 * Splits a wire-format buffer into an AndroidLogEntry
478 * entry allocated by caller. Pointers will point directly into buf
479 *
480 * Returns 0 on success and -1 on invalid wire format (entry will be
481 * in unspecified state)
482 */
Mark Salyzynbe1d3c22016-03-10 08:25:33 -0800483LIBLOG_ABI_PUBLIC int android_log_processLogBuffer(
484 struct logger_entry *buf,
485 AndroidLogEntry *entry)
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -0700486{
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -0700487 entry->tv_sec = buf->sec;
488 entry->tv_nsec = buf->nsec;
Mark Salyzyn90e7af32015-12-07 16:52:42 -0800489 entry->uid = -1;
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -0700490 entry->pid = buf->pid;
491 entry->tid = buf->tid;
Kenny Root4bf3c022011-09-30 17:10:14 -0700492
493 /*
494 * format: <priority:1><tag:N>\0<message:N>\0
495 *
496 * tag str
Nick Kraleviche1ede152011-10-18 15:23:33 -0700497 * starts at buf->msg+1
Kenny Root4bf3c022011-09-30 17:10:14 -0700498 * msg
Nick Kraleviche1ede152011-10-18 15:23:33 -0700499 * starts at buf->msg+1+len(tag)+1
Jeff Sharkeya820a0e2011-10-26 18:40:39 -0700500 *
501 * The message may have been truncated by the kernel log driver.
502 * When that happens, we must null-terminate the message ourselves.
Kenny Root4bf3c022011-09-30 17:10:14 -0700503 */
Nick Kraleviche1ede152011-10-18 15:23:33 -0700504 if (buf->len < 3) {
Mark Salyzynb932b2f2015-05-15 09:01:58 -0700505 /*
506 * An well-formed entry must consist of at least a priority
507 * and two null characters
508 */
Nick Kraleviche1ede152011-10-18 15:23:33 -0700509 fprintf(stderr, "+++ LOG: entry too small\n");
Kenny Root4bf3c022011-09-30 17:10:14 -0700510 return -1;
511 }
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -0700512
Jeff Sharkeya820a0e2011-10-26 18:40:39 -0700513 int msgStart = -1;
514 int msgEnd = -1;
515
Nick Kraleviche1ede152011-10-18 15:23:33 -0700516 int i;
Mark Salyzyn40b21552013-12-18 12:59:01 -0800517 char *msg = buf->msg;
518 struct logger_entry_v2 *buf2 = (struct logger_entry_v2 *)buf;
519 if (buf2->hdr_size) {
Mark Salyzyn305374c2016-08-18 14:59:41 -0700520 if ((buf2->hdr_size < sizeof(((struct log_msg *)NULL)->entry_v1)) ||
521 (buf2->hdr_size > sizeof(((struct log_msg *)NULL)->entry))) {
522 fprintf(stderr, "+++ LOG: entry illegal hdr_size\n");
523 return -1;
524 }
Mark Salyzyn40b21552013-12-18 12:59:01 -0800525 msg = ((char *)buf2) + buf2->hdr_size;
Mark Salyzyn90e7af32015-12-07 16:52:42 -0800526 if (buf2->hdr_size >= sizeof(struct logger_entry_v4)) {
527 entry->uid = ((struct logger_entry_v4 *)buf)->uid;
528 }
Mark Salyzyn40b21552013-12-18 12:59:01 -0800529 }
Nick Kraleviche1ede152011-10-18 15:23:33 -0700530 for (i = 1; i < buf->len; i++) {
Mark Salyzyn40b21552013-12-18 12:59:01 -0800531 if (msg[i] == '\0') {
Jeff Sharkeya820a0e2011-10-26 18:40:39 -0700532 if (msgStart == -1) {
533 msgStart = i + 1;
534 } else {
535 msgEnd = i;
536 break;
537 }
Nick Kraleviche1ede152011-10-18 15:23:33 -0700538 }
539 }
Jeff Sharkeya820a0e2011-10-26 18:40:39 -0700540
541 if (msgStart == -1) {
Mark Salyzyn083c5342016-03-21 09:45:34 -0700542 /* +++ LOG: malformed log message, DYB */
543 for (i = 1; i < buf->len; i++) {
544 /* odd characters in tag? */
545 if ((msg[i] <= ' ') || (msg[i] == ':') || (msg[i] >= 0x7f)) {
546 msg[i] = '\0';
547 msgStart = i + 1;
548 break;
549 }
550 }
551 if (msgStart == -1) {
552 msgStart = buf->len - 1; /* All tag, no message, print truncates */
553 }
Nick Kralevich63f4a842011-10-17 10:45:03 -0700554 }
Jeff Sharkeya820a0e2011-10-26 18:40:39 -0700555 if (msgEnd == -1) {
Mark Salyzynb932b2f2015-05-15 09:01:58 -0700556 /* incoming message not null-terminated; force it */
Mark Salyzynd7bcf402015-12-04 09:24:15 -0800557 msgEnd = buf->len - 1; /* may result in msgEnd < msgStart */
Mark Salyzyn40b21552013-12-18 12:59:01 -0800558 msg[msgEnd] = '\0';
Jeff Sharkeya820a0e2011-10-26 18:40:39 -0700559 }
560
Mark Salyzyn40b21552013-12-18 12:59:01 -0800561 entry->priority = msg[0];
562 entry->tag = msg + 1;
Mark Salyzyn807e40e2016-09-22 09:56:51 -0700563 entry->tagLen = msgStart - 1;
Mark Salyzyn40b21552013-12-18 12:59:01 -0800564 entry->message = msg + msgStart;
Mark Salyzynd7bcf402015-12-04 09:24:15 -0800565 entry->messageLen = (msgEnd < msgStart) ? 0 : (msgEnd - msgStart);
Nick Kralevich63f4a842011-10-17 10:45:03 -0700566
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -0700567 return 0;
568}
569
570/*
Mark Salyzyn8470dad2015-03-06 20:42:57 +0000571 * Extract a 4-byte value from a byte stream.
572 */
573static inline uint32_t get4LE(const uint8_t* src)
574{
575 return src[0] | (src[1] << 8) | (src[2] << 16) | (src[3] << 24);
576}
577
578/*
579 * Extract an 8-byte value from a byte stream.
580 */
581static inline uint64_t get8LE(const uint8_t* src)
582{
583 uint32_t low, high;
584
585 low = src[0] | (src[1] << 8) | (src[2] << 16) | (src[3] << 24);
586 high = src[4] | (src[5] << 8) | (src[6] << 16) | (src[7] << 24);
Jeff Brown44193d92015-04-28 12:47:02 -0700587 return ((uint64_t) high << 32) | (uint64_t) low;
Mark Salyzyn8470dad2015-03-06 20:42:57 +0000588}
589
Mark Salyzyn4fd05072016-10-18 11:30:11 -0700590static bool findChar(const char** cp, size_t* len, int c) {
591 while (*len && isspace(**cp)) {
592 ++*cp;
593 --*len;
594 }
595 if (c == INT_MAX) return *len;
596 if (*len && (**cp == c)) {
597 ++*cp;
598 --*len;
599 return true;
600 }
601 return false;
602}
Mark Salyzyn8470dad2015-03-06 20:42:57 +0000603
604/*
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -0700605 * Recursively convert binary log data to printable form.
606 *
607 * This needs to be recursive because you can have lists of lists.
608 *
609 * If we run out of room, we stop processing immediately. It's important
610 * for us to check for space on every output element to avoid producing
611 * garbled output.
612 *
613 * Returns 0 on success, 1 on buffer full, -1 on failure.
614 */
Mark Salyzyn4fd05072016-10-18 11:30:11 -0700615enum objectType {
616 TYPE_OBJECTS = '1',
617 TYPE_BYTES = '2',
618 TYPE_MILLISECONDS = '3',
619 TYPE_ALLOCATIONS = '4',
620 TYPE_ID = '5',
621 TYPE_PERCENT = '6'
622};
623
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -0700624static int android_log_printBinaryEvent(const unsigned char** pEventData,
Mark Salyzyn4fd05072016-10-18 11:30:11 -0700625 size_t* pEventDataLen, char** pOutBuf, size_t* pOutBufLen,
626 const char** fmtStr, size_t* fmtLen)
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -0700627{
628 const unsigned char* eventData = *pEventData;
629 size_t eventDataLen = *pEventDataLen;
630 char* outBuf = *pOutBuf;
Mark Salyzyn4fd05072016-10-18 11:30:11 -0700631 char* outBufSave = outBuf;
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -0700632 size_t outBufLen = *pOutBufLen;
Mark Salyzyn4fd05072016-10-18 11:30:11 -0700633 size_t outBufLenSave = outBufLen;
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -0700634 unsigned char type;
635 size_t outCount;
636 int result = 0;
Mark Salyzyn4fd05072016-10-18 11:30:11 -0700637 const char* cp;
638 size_t len;
639 int64_t lval;
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -0700640
Mark Salyzyn1a57ae32016-11-11 14:41:30 -0800641 if (eventDataLen < 1) return -1;
642
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -0700643 type = *eventData++;
644 eventDataLen--;
645
Mark Salyzyn4fd05072016-10-18 11:30:11 -0700646 cp = NULL;
647 len = 0;
648 if (fmtStr && *fmtStr && fmtLen && *fmtLen && **fmtStr) {
649 cp = *fmtStr;
650 len = *fmtLen;
651 }
652 /*
653 * event.logtag format specification:
654 *
655 * Optionally, after the tag names can be put a description for the value(s)
656 * of the tag. Description are in the format
657 * (<name>|data type[|data unit])
658 * Multiple values are separated by commas.
659 *
660 * The data type is a number from the following values:
661 * 1: int
662 * 2: long
663 * 3: string
664 * 4: list
665 * 5: float
666 *
667 * The data unit is a number taken from the following list:
668 * 1: Number of objects
669 * 2: Number of bytes
670 * 3: Number of milliseconds
671 * 4: Number of allocations
672 * 5: Id
673 * 6: Percent
674 * Default value for data of type int/long is 2 (bytes).
675 */
676 if (!cp || !findChar(&cp, &len, '(')) {
677 len = 0;
678 } else {
679 char* outBufLastSpace = NULL;
680
681 findChar(&cp, &len, INT_MAX);
682 while (len && *cp && (*cp != '|') && (*cp != ')')) {
683 if (outBufLen <= 0) {
684 /* halt output */
685 goto no_room;
686 }
687 outBufLastSpace = isspace(*cp) ? outBuf : NULL;
688 *outBuf = *cp;
689 ++outBuf;
690 ++cp;
691 --outBufLen;
692 --len;
693 }
694 if (outBufLastSpace) {
695 outBufLen += outBuf - outBufLastSpace;
696 outBuf = outBufLastSpace;
697 }
698 if (outBufLen <= 0) {
699 /* halt output */
700 goto no_room;
701 }
702 if (outBufSave != outBuf) {
703 *outBuf = '=';
704 ++outBuf;
705 --outBufLen;
706 }
707
708 if (findChar(&cp, &len, '|') && findChar(&cp, &len, INT_MAX)) {
709 static const unsigned char typeTable[] = {
710 EVENT_TYPE_INT,
711 EVENT_TYPE_LONG,
712 EVENT_TYPE_STRING,
713 EVENT_TYPE_LIST,
714 EVENT_TYPE_FLOAT
715 };
716
717 if ((*cp >= '1') &&
718 (*cp < (char)('1' + (sizeof(typeTable) / sizeof(typeTable[0])))) &&
719 (type != typeTable[(size_t)(*cp - '1')])) len = 0;
720
721 if (len) {
722 ++cp;
723 --len;
724 } else {
725 /* reset the format */
726 outBuf = outBufSave;
727 outBufLen = outBufLenSave;
728 }
729 }
730 }
731 lval = 0;
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -0700732 switch (type) {
733 case EVENT_TYPE_INT:
734 /* 32-bit signed int */
735 {
Mark Salyzyn4fd05072016-10-18 11:30:11 -0700736 int32_t ival;
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -0700737
Mark Salyzyn1a57ae32016-11-11 14:41:30 -0800738 if (eventDataLen < 4) return -1;
Mark Salyzyn8470dad2015-03-06 20:42:57 +0000739 ival = get4LE(eventData);
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -0700740 eventData += 4;
741 eventDataLen -= 4;
742
Mark Salyzyn4fd05072016-10-18 11:30:11 -0700743 lval = ival;
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -0700744 }
Mark Salyzyn4fd05072016-10-18 11:30:11 -0700745 goto pr_lval;
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -0700746 case EVENT_TYPE_LONG:
747 /* 64-bit signed long */
Mark Salyzyn1a57ae32016-11-11 14:41:30 -0800748 if (eventDataLen < 8) return -1;
Mark Salyzyn4fd05072016-10-18 11:30:11 -0700749 lval = get8LE(eventData);
750 eventData += 8;
751 eventDataLen -= 8;
752 pr_lval:
753 outCount = snprintf(outBuf, outBufLen, "%" PRId64, lval);
754 if (outCount < outBufLen) {
755 outBuf += outCount;
756 outBufLen -= outCount;
757 } else {
758 /* halt output */
759 goto no_room;
Jeff Brown44193d92015-04-28 12:47:02 -0700760 }
761 break;
762 case EVENT_TYPE_FLOAT:
763 /* float */
764 {
765 uint32_t ival;
766 float fval;
767
Mark Salyzyn1a57ae32016-11-11 14:41:30 -0800768 if (eventDataLen < 4) return -1;
Jeff Brown44193d92015-04-28 12:47:02 -0700769 ival = get4LE(eventData);
770 fval = *(float*)&ival;
771 eventData += 4;
772 eventDataLen -= 4;
773
774 outCount = snprintf(outBuf, outBufLen, "%f", fval);
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -0700775 if (outCount < outBufLen) {
776 outBuf += outCount;
777 outBufLen -= outCount;
778 } else {
779 /* halt output */
780 goto no_room;
781 }
782 }
783 break;
784 case EVENT_TYPE_STRING:
785 /* UTF-8 chars, not NULL-terminated */
786 {
787 unsigned int strLen;
788
Mark Salyzyn1a57ae32016-11-11 14:41:30 -0800789 if (eventDataLen < 4) return -1;
Mark Salyzyn8470dad2015-03-06 20:42:57 +0000790 strLen = get4LE(eventData);
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -0700791 eventData += 4;
792 eventDataLen -= 4;
793
Mark Salyzyn1a57ae32016-11-11 14:41:30 -0800794 if (eventDataLen < strLen) return -1;
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -0700795
Mark Salyzyn4fd05072016-10-18 11:30:11 -0700796 if (cp && (strLen == 0)) {
797 /* reset the format if no content */
798 outBuf = outBufSave;
799 outBufLen = outBufLenSave;
800 }
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -0700801 if (strLen < outBufLen) {
802 memcpy(outBuf, eventData, strLen);
803 outBuf += strLen;
804 outBufLen -= strLen;
805 } else if (outBufLen > 0) {
806 /* copy what we can */
807 memcpy(outBuf, eventData, outBufLen);
808 outBuf += outBufLen;
809 outBufLen -= outBufLen;
810 goto no_room;
811 }
812 eventData += strLen;
813 eventDataLen -= strLen;
814 break;
815 }
816 case EVENT_TYPE_LIST:
817 /* N items, all different types */
818 {
819 unsigned char count;
820 int i;
821
Mark Salyzyn1a57ae32016-11-11 14:41:30 -0800822 if (eventDataLen < 1) return -1;
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -0700823
824 count = *eventData++;
825 eventDataLen--;
826
Mark Salyzyn1a57ae32016-11-11 14:41:30 -0800827 if (outBufLen <= 0) goto no_room;
828
829 *outBuf++ = '[';
830 outBufLen--;
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -0700831
832 for (i = 0; i < count; i++) {
833 result = android_log_printBinaryEvent(&eventData, &eventDataLen,
Mark Salyzyn4fd05072016-10-18 11:30:11 -0700834 &outBuf, &outBufLen, fmtStr, fmtLen);
Mark Salyzyn1a57ae32016-11-11 14:41:30 -0800835 if (result != 0) goto bail;
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -0700836
Mark Salyzyn1a57ae32016-11-11 14:41:30 -0800837 if (i < (count - 1)) {
838 if (outBufLen <= 0) goto no_room;
839 *outBuf++ = ',';
840 outBufLen--;
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -0700841 }
842 }
843
Mark Salyzyn1a57ae32016-11-11 14:41:30 -0800844 if (outBufLen <= 0) goto no_room;
845
846 *outBuf++ = ']';
847 outBufLen--;
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -0700848 }
849 break;
850 default:
851 fprintf(stderr, "Unknown binary event type %d\n", type);
852 return -1;
853 }
Mark Salyzyn4fd05072016-10-18 11:30:11 -0700854 if (cp && len) {
855 if (findChar(&cp, &len, '|') && findChar(&cp, &len, INT_MAX)) {
856 switch (*cp) {
857 case TYPE_OBJECTS:
858 outCount = 0;
859 /* outCount = snprintf(outBuf, outBufLen, " objects"); */
860 break;
861 case TYPE_BYTES:
862 if ((lval != 0) && ((lval % 1024) == 0)) {
863 /* repaint with multiplier */
864 static const char suffixTable[] = { 'K', 'M', 'G', 'T' };
865 size_t idx = 0;
866 outBuf -= outCount;
867 outBufLen += outCount;
868 do {
869 lval /= 1024;
870 if ((lval % 1024) != 0) break;
871 } while (++idx < ((sizeof(suffixTable) /
872 sizeof(suffixTable[0])) - 1));
873 outCount = snprintf(outBuf, outBufLen,
874 "%" PRId64 "%cB",
875 lval, suffixTable[idx]);
876 } else {
877 outCount = snprintf(outBuf, outBufLen, "B");
878 }
879 break;
880 case TYPE_MILLISECONDS:
881 if (((lval <= -1000) || (1000 <= lval)) &&
882 (outBufLen || (outBuf[-1] == '0'))) {
883 /* repaint as (fractional) seconds, possibly saving space */
884 if (outBufLen) outBuf[0] = outBuf[-1];
885 outBuf[-1] = outBuf[-2];
886 outBuf[-2] = outBuf[-3];
887 outBuf[-3] = '.';
888 while ((outBufLen == 0) || (*outBuf == '0')) {
889 --outBuf;
890 ++outBufLen;
891 }
892 if (*outBuf != '.') {
893 ++outBuf;
894 --outBufLen;
895 }
896 outCount = snprintf(outBuf, outBufLen, "s");
897 } else {
898 outCount = snprintf(outBuf, outBufLen, "ms");
899 }
900 break;
901 case TYPE_ALLOCATIONS:
902 outCount = 0;
903 /* outCount = snprintf(outBuf, outBufLen, " allocations"); */
904 break;
905 case TYPE_ID:
906 outCount = 0;
907 break;
908 case TYPE_PERCENT:
909 outCount = snprintf(outBuf, outBufLen, "%%");
910 break;
911 default: /* ? */
912 outCount = 0;
913 break;
914 }
915 ++cp;
916 --len;
917 if (outCount < outBufLen) {
918 outBuf += outCount;
919 outBufLen -= outCount;
920 } else if (outCount) {
921 /* halt output */
922 goto no_room;
923 }
924 }
925 if (!findChar(&cp, &len, ')')) len = 0;
926 if (!findChar(&cp, &len, ',')) len = 0;
927 }
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -0700928
929bail:
930 *pEventData = eventData;
931 *pEventDataLen = eventDataLen;
932 *pOutBuf = outBuf;
933 *pOutBufLen = outBufLen;
Mark Salyzyn4fd05072016-10-18 11:30:11 -0700934 if (cp) {
935 *fmtStr = cp;
936 *fmtLen = len;
937 }
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -0700938 return result;
939
940no_room:
941 result = 1;
942 goto bail;
943}
944
945/**
946 * Convert a binary log entry to ASCII form.
947 *
948 * For convenience we mimic the processLogBuffer API. There is no
949 * pre-defined output length for the binary data, since we're free to format
950 * it however we choose, which means we can't really use a fixed-size buffer
951 * here.
952 */
Mark Salyzynbe1d3c22016-03-10 08:25:33 -0800953LIBLOG_ABI_PUBLIC int android_log_processBinaryLogBuffer(
954 struct logger_entry *buf,
955 AndroidLogEntry *entry,
956 const EventTagMap *map,
957 char *messageBuf, int messageBufLen)
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -0700958{
959 size_t inCount;
Mark Salyzyn4fd05072016-10-18 11:30:11 -0700960 uint32_t tagIndex;
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -0700961 const unsigned char* eventData;
962
963 entry->tv_sec = buf->sec;
964 entry->tv_nsec = buf->nsec;
965 entry->priority = ANDROID_LOG_INFO;
Mark Salyzyn90e7af32015-12-07 16:52:42 -0800966 entry->uid = -1;
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -0700967 entry->pid = buf->pid;
968 entry->tid = buf->tid;
969
970 /*
Mark Salyzyn7bc80232015-12-11 12:32:53 -0800971 * Pull the tag out, fill in some additional details based on incoming
972 * buffer version (v3 adds lid, v4 adds uid).
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -0700973 */
974 eventData = (const unsigned char*) buf->msg;
Mark Salyzyn40b21552013-12-18 12:59:01 -0800975 struct logger_entry_v2 *buf2 = (struct logger_entry_v2 *)buf;
976 if (buf2->hdr_size) {
Mark Salyzyn305374c2016-08-18 14:59:41 -0700977 if ((buf2->hdr_size < sizeof(((struct log_msg *)NULL)->entry_v1)) ||
978 (buf2->hdr_size > sizeof(((struct log_msg *)NULL)->entry))) {
979 fprintf(stderr, "+++ LOG: entry illegal hdr_size\n");
980 return -1;
981 }
Mark Salyzyn40b21552013-12-18 12:59:01 -0800982 eventData = ((unsigned char *)buf2) + buf2->hdr_size;
Mark Salyzyn7bc80232015-12-11 12:32:53 -0800983 if ((buf2->hdr_size >= sizeof(struct logger_entry_v3)) &&
984 (((struct logger_entry_v3 *)buf)->lid == LOG_ID_SECURITY)) {
985 entry->priority = ANDROID_LOG_WARN;
986 }
Mark Salyzyn90e7af32015-12-07 16:52:42 -0800987 if (buf2->hdr_size >= sizeof(struct logger_entry_v4)) {
988 entry->uid = ((struct logger_entry_v4 *)buf)->uid;
989 }
Mark Salyzyn40b21552013-12-18 12:59:01 -0800990 }
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -0700991 inCount = buf->len;
Mark Salyzyn1a57ae32016-11-11 14:41:30 -0800992 if (inCount < 4) return -1;
Mark Salyzyn8470dad2015-03-06 20:42:57 +0000993 tagIndex = get4LE(eventData);
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -0700994 eventData += 4;
995 inCount -= 4;
996
Mark Salyzyn807e40e2016-09-22 09:56:51 -0700997 entry->tagLen = 0;
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -0700998 if (map != NULL) {
Mark Salyzyn807e40e2016-09-22 09:56:51 -0700999 entry->tag = android_lookupEventTag_len(map, &entry->tagLen, tagIndex);
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -07001000 } else {
1001 entry->tag = NULL;
1002 }
1003
1004 /*
1005 * If we don't have a map, or didn't find the tag number in the map,
1006 * stuff a generated tag value into the start of the output buffer and
1007 * shift the buffer pointers down.
1008 */
1009 if (entry->tag == NULL) {
Mark Salyzyn807e40e2016-09-22 09:56:51 -07001010 size_t tagLen;
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -07001011
Mark Salyzyn4fd05072016-10-18 11:30:11 -07001012 tagLen = snprintf(messageBuf, messageBufLen, "[%" PRIu32 "]", tagIndex);
Mark Salyzyn807e40e2016-09-22 09:56:51 -07001013 if (tagLen >= (size_t)messageBufLen) {
1014 tagLen = messageBufLen - 1;
1015 }
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -07001016 entry->tag = messageBuf;
Mark Salyzyn807e40e2016-09-22 09:56:51 -07001017 entry->tagLen = tagLen;
1018 messageBuf += tagLen + 1;
1019 messageBufLen -= tagLen + 1;
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -07001020 }
1021
1022 /*
1023 * Format the event log data into the buffer.
1024 */
Mark Salyzyn4fd05072016-10-18 11:30:11 -07001025 const char* fmtStr = NULL;
1026 size_t fmtLen = 0;
1027 if (descriptive_output && map) {
1028 fmtStr = android_lookupEventFormat_len(map, &fmtLen, tagIndex);
1029 }
Mark Salyzyn1a57ae32016-11-11 14:41:30 -08001030
1031 char* outBuf = messageBuf;
1032 size_t outRemaining = messageBufLen - 1; /* leave one for nul byte */
1033 int result = 0;
1034
1035 if ((inCount > 0) || fmtLen) {
1036 result = android_log_printBinaryEvent(&eventData, &inCount, &outBuf,
1037 &outRemaining, &fmtStr, &fmtLen);
1038 }
Mark Salyzyn4fd05072016-10-18 11:30:11 -07001039 if ((result == 1) && fmtStr) {
1040 /* We overflowed :-(, let's repaint the line w/o format dressings */
1041 eventData = (const unsigned char*)buf->msg;
1042 if (buf2->hdr_size) {
1043 eventData = ((unsigned char *)buf2) + buf2->hdr_size;
1044 }
1045 eventData += 4;
1046 outBuf = messageBuf;
1047 outRemaining = messageBufLen - 1;
1048 result = android_log_printBinaryEvent(&eventData, &inCount, &outBuf,
1049 &outRemaining, NULL, NULL);
1050 }
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -07001051 if (result < 0) {
1052 fprintf(stderr, "Binary log entry conversion failed\n");
Mark Salyzyn1a57ae32016-11-11 14:41:30 -08001053 }
1054 if (result) {
1055 if (!outRemaining) {
1056 /* make space to leave an indicator */
1057 --outBuf;
1058 ++outRemaining;
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -07001059 }
Mark Salyzyn1a57ae32016-11-11 14:41:30 -08001060 *outBuf++ = (result < 0) ? '!' : '^'; /* Error or Truncation? */
1061 outRemaining--;
1062 /* pretend we ate all the data to prevent log stutter */
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -07001063 inCount = 0;
Mark Salyzyn538bc122016-11-16 15:28:31 -08001064 if (result > 0) result = 0;
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -07001065 }
1066
1067 /* eat the silly terminating '\n' */
1068 if (inCount == 1 && *eventData == '\n') {
1069 eventData++;
1070 inCount--;
1071 }
1072
1073 if (inCount != 0) {
1074 fprintf(stderr,
Andrew Hsiehd2c8f522012-02-27 16:48:18 -08001075 "Warning: leftover binary log data (%zu bytes)\n", inCount);
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -07001076 }
1077
1078 /*
1079 * Terminate the buffer. The NUL byte does not count as part of
1080 * entry->messageLen.
1081 */
1082 *outBuf = '\0';
1083 entry->messageLen = outBuf - messageBuf;
1084 assert(entry->messageLen == (messageBufLen-1) - outRemaining);
1085
1086 entry->message = messageBuf;
1087
Mark Salyzyn538bc122016-11-16 15:28:31 -08001088 return result;
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -07001089}
1090
Mark Salyzynb932b2f2015-05-15 09:01:58 -07001091/*
1092 * One utf8 character at a time
1093 *
1094 * Returns the length of the utf8 character in the buffer,
1095 * or -1 if illegal or truncated
1096 *
1097 * Open coded from libutils/Unicode.cpp, borrowed from utf8_length(),
1098 * can not remove from here because of library circular dependencies.
1099 * Expect one-day utf8_character_length with the same signature could
1100 * _also_ be part of libutils/Unicode.cpp if its usefullness needs to
1101 * propagate globally.
1102 */
Mark Salyzynbe1d3c22016-03-10 08:25:33 -08001103LIBLOG_WEAK ssize_t utf8_character_length(const char *src, size_t len)
Mark Salyzynb932b2f2015-05-15 09:01:58 -07001104{
1105 const char *cur = src;
1106 const char first_char = *cur++;
1107 static const uint32_t kUnicodeMaxCodepoint = 0x0010FFFF;
1108 int32_t mask, to_ignore_mask;
1109 size_t num_to_read;
1110 uint32_t utf32;
1111
1112 if ((first_char & 0x80) == 0) { /* ASCII */
Mark Salyzynfaa92e92015-09-08 07:57:27 -07001113 return first_char ? 1 : -1;
Mark Salyzynb932b2f2015-05-15 09:01:58 -07001114 }
1115
1116 /*
1117 * (UTF-8's character must not be like 10xxxxxx,
1118 * but 110xxxxx, 1110xxxx, ... or 1111110x)
1119 */
1120 if ((first_char & 0x40) == 0) {
1121 return -1;
1122 }
1123
1124 for (utf32 = 1, num_to_read = 1, mask = 0x40, to_ignore_mask = 0x80;
1125 num_to_read < 5 && (first_char & mask);
1126 num_to_read++, to_ignore_mask |= mask, mask >>= 1) {
1127 if (num_to_read > len) {
1128 return -1;
1129 }
1130 if ((*cur & 0xC0) != 0x80) { /* can not be 10xxxxxx? */
1131 return -1;
1132 }
1133 utf32 = (utf32 << 6) + (*cur++ & 0b00111111);
1134 }
1135 /* "first_char" must be (110xxxxx - 11110xxx) */
1136 if (num_to_read >= 5) {
1137 return -1;
1138 }
1139 to_ignore_mask |= mask;
1140 utf32 |= ((~to_ignore_mask) & first_char) << (6 * (num_to_read - 1));
1141 if (utf32 > kUnicodeMaxCodepoint) {
1142 return -1;
1143 }
1144 return num_to_read;
1145}
1146
1147/*
1148 * Convert to printable from message to p buffer, return string length. If p is
1149 * NULL, do not copy, but still return the expected string length.
1150 */
1151static size_t convertPrintable(char *p, const char *message, size_t messageLen)
1152{
1153 char *begin = p;
1154 bool print = p != NULL;
1155
1156 while (messageLen) {
1157 char buf[6];
1158 ssize_t len = sizeof(buf) - 1;
1159 if ((size_t)len > messageLen) {
1160 len = messageLen;
1161 }
1162 len = utf8_character_length(message, len);
1163
1164 if (len < 0) {
1165 snprintf(buf, sizeof(buf),
1166 ((messageLen > 1) && isdigit(message[1]))
1167 ? "\\%03o"
1168 : "\\%o",
1169 *message & 0377);
1170 len = 1;
1171 } else {
1172 buf[0] = '\0';
1173 if (len == 1) {
1174 if (*message == '\a') {
1175 strcpy(buf, "\\a");
1176 } else if (*message == '\b') {
1177 strcpy(buf, "\\b");
1178 } else if (*message == '\t') {
Mark Salyzyn65d5ca22015-11-18 09:58:00 -08001179 strcpy(buf, "\t"); // Do not escape tabs
Mark Salyzynb932b2f2015-05-15 09:01:58 -07001180 } else if (*message == '\v') {
1181 strcpy(buf, "\\v");
1182 } else if (*message == '\f') {
1183 strcpy(buf, "\\f");
1184 } else if (*message == '\r') {
1185 strcpy(buf, "\\r");
1186 } else if (*message == '\\') {
1187 strcpy(buf, "\\\\");
1188 } else if ((*message < ' ') || (*message & 0x80)) {
1189 snprintf(buf, sizeof(buf), "\\%o", *message & 0377);
1190 }
1191 }
1192 if (!buf[0]) {
1193 strncpy(buf, message, len);
1194 buf[len] = '\0';
1195 }
1196 }
1197 if (print) {
1198 strcpy(p, buf);
1199 }
1200 p += strlen(buf);
1201 message += len;
1202 messageLen -= len;
1203 }
1204 return p - begin;
1205}
1206
Mark Salyzynbe1d3c22016-03-10 08:25:33 -08001207static char *readSeconds(char *e, struct timespec *t)
Mark Salyzyn4cbed022015-08-31 15:53:41 -07001208{
1209 unsigned long multiplier;
1210 char *p;
1211 t->tv_sec = strtoul(e, &p, 10);
1212 if (*p != '.') {
1213 return NULL;
1214 }
1215 t->tv_nsec = 0;
1216 multiplier = NS_PER_SEC;
1217 while (isdigit(*++p) && (multiplier /= 10)) {
1218 t->tv_nsec += (*p - '0') * multiplier;
1219 }
1220 return p;
1221}
1222
1223static struct timespec *sumTimespec(struct timespec *left,
1224 struct timespec *right)
1225{
1226 left->tv_nsec += right->tv_nsec;
1227 left->tv_sec += right->tv_sec;
1228 if (left->tv_nsec >= (long)NS_PER_SEC) {
1229 left->tv_nsec -= NS_PER_SEC;
1230 left->tv_sec += 1;
1231 }
1232 return left;
1233}
1234
1235static struct timespec *subTimespec(struct timespec *result,
1236 struct timespec *left,
1237 struct timespec *right)
1238{
1239 result->tv_nsec = left->tv_nsec - right->tv_nsec;
1240 result->tv_sec = left->tv_sec - right->tv_sec;
1241 if (result->tv_nsec < 0) {
1242 result->tv_nsec += NS_PER_SEC;
1243 result->tv_sec -= 1;
1244 }
1245 return result;
1246}
1247
1248static long long nsecTimespec(struct timespec *now)
1249{
1250 return (long long)now->tv_sec * NS_PER_SEC + now->tv_nsec;
1251}
1252
1253static void convertMonotonic(struct timespec *result,
1254 const AndroidLogEntry *entry)
1255{
1256 struct listnode *node;
1257 struct conversionList {
1258 struct listnode node; /* first */
1259 struct timespec time;
1260 struct timespec convert;
1261 } *list, *next;
1262 struct timespec time, convert;
1263
1264 /* If we do not have a conversion list, build one up */
1265 if (list_empty(&convertHead)) {
1266 bool suspended_pending = false;
1267 struct timespec suspended_monotonic = { 0, 0 };
1268 struct timespec suspended_diff = { 0, 0 };
1269
1270 /*
1271 * Read dmesg for _some_ synchronization markers and insert
1272 * Anything in the Android Logger before the dmesg logging span will
1273 * be highly suspect regarding the monotonic time calculations.
1274 */
Mark Salyzyn78786da2016-04-28 16:06:24 -07001275 FILE *p = popen("/system/bin/dmesg", "re");
Mark Salyzyn4cbed022015-08-31 15:53:41 -07001276 if (p) {
1277 char *line = NULL;
1278 size_t len = 0;
1279 while (getline(&line, &len, p) > 0) {
1280 static const char suspend[] = "PM: suspend entry ";
1281 static const char resume[] = "PM: suspend exit ";
1282 static const char healthd[] = "healthd";
1283 static const char battery[] = ": battery ";
1284 static const char suspended[] = "Suspended for ";
1285 struct timespec monotonic;
1286 struct tm tm;
1287 char *cp, *e = line;
1288 bool add_entry = true;
1289
1290 if (*e == '<') {
1291 while (*e && (*e != '>')) {
1292 ++e;
1293 }
1294 if (*e != '>') {
1295 continue;
1296 }
1297 }
1298 if (*e != '[') {
1299 continue;
1300 }
1301 while (*++e == ' ') {
1302 ;
1303 }
1304 e = readSeconds(e, &monotonic);
1305 if (!e || (*e != ']')) {
1306 continue;
1307 }
1308
1309 if ((e = strstr(e, suspend))) {
1310 e += sizeof(suspend) - 1;
1311 } else if ((e = strstr(line, resume))) {
1312 e += sizeof(resume) - 1;
1313 } else if (((e = strstr(line, healthd)))
1314 && ((e = strstr(e + sizeof(healthd) - 1, battery)))) {
1315 /* NB: healthd is roughly 150us late, worth the price to
1316 * deal with ntp-induced or hardware clock drift. */
1317 e += sizeof(battery) - 1;
1318 } else if ((e = strstr(line, suspended))) {
1319 e += sizeof(suspended) - 1;
1320 e = readSeconds(e, &time);
1321 if (!e) {
1322 continue;
1323 }
1324 add_entry = false;
1325 suspended_pending = true;
1326 suspended_monotonic = monotonic;
1327 suspended_diff = time;
1328 } else {
1329 continue;
1330 }
1331 if (add_entry) {
1332 /* look for "????-??-?? ??:??:??.????????? UTC" */
1333 cp = strstr(e, " UTC");
1334 if (!cp || ((cp - e) < 29) || (cp[-10] != '.')) {
1335 continue;
1336 }
1337 e = cp - 29;
1338 cp = readSeconds(cp - 10, &time);
1339 if (!cp) {
1340 continue;
1341 }
1342 cp = strptime(e, "%Y-%m-%d %H:%M:%S.", &tm);
1343 if (!cp) {
1344 continue;
1345 }
1346 cp = getenv(tz);
1347 if (cp) {
1348 cp = strdup(cp);
1349 }
1350 setenv(tz, utc, 1);
1351 time.tv_sec = mktime(&tm);
1352 if (cp) {
1353 setenv(tz, cp, 1);
1354 free(cp);
1355 } else {
1356 unsetenv(tz);
1357 }
1358 list = calloc(1, sizeof(struct conversionList));
1359 list_init(&list->node);
1360 list->time = time;
1361 subTimespec(&list->convert, &time, &monotonic);
1362 list_add_tail(&convertHead, &list->node);
1363 }
1364 if (suspended_pending && !list_empty(&convertHead)) {
1365 list = node_to_item(list_tail(&convertHead),
1366 struct conversionList, node);
1367 if (subTimespec(&time,
1368 subTimespec(&time,
1369 &list->time,
1370 &list->convert),
1371 &suspended_monotonic)->tv_sec > 0) {
1372 /* resume, what is convert factor before? */
1373 subTimespec(&convert, &list->convert, &suspended_diff);
1374 } else {
1375 /* suspend */
1376 convert = list->convert;
1377 }
1378 time = suspended_monotonic;
1379 sumTimespec(&time, &convert);
1380 /* breakpoint just before sleep */
1381 list = calloc(1, sizeof(struct conversionList));
1382 list_init(&list->node);
1383 list->time = time;
1384 list->convert = convert;
1385 list_add_tail(&convertHead, &list->node);
1386 /* breakpoint just after sleep */
1387 list = calloc(1, sizeof(struct conversionList));
1388 list_init(&list->node);
1389 list->time = time;
1390 sumTimespec(&list->time, &suspended_diff);
1391 list->convert = convert;
1392 sumTimespec(&list->convert, &suspended_diff);
1393 list_add_tail(&convertHead, &list->node);
1394 suspended_pending = false;
1395 }
1396 }
1397 pclose(p);
1398 }
1399 /* last entry is our current time conversion */
1400 list = calloc(1, sizeof(struct conversionList));
1401 list_init(&list->node);
1402 clock_gettime(CLOCK_REALTIME, &list->time);
1403 clock_gettime(CLOCK_MONOTONIC, &convert);
1404 clock_gettime(CLOCK_MONOTONIC, &time);
1405 /* Correct for instant clock_gettime latency (syscall or ~30ns) */
1406 subTimespec(&time, &convert, subTimespec(&time, &time, &convert));
1407 /* Calculate conversion factor */
1408 subTimespec(&list->convert, &list->time, &time);
1409 list_add_tail(&convertHead, &list->node);
1410 if (suspended_pending) {
1411 /* manufacture a suspend @ point before */
1412 subTimespec(&convert, &list->convert, &suspended_diff);
1413 time = suspended_monotonic;
1414 sumTimespec(&time, &convert);
1415 /* breakpoint just after sleep */
1416 list = calloc(1, sizeof(struct conversionList));
1417 list_init(&list->node);
1418 list->time = time;
1419 sumTimespec(&list->time, &suspended_diff);
1420 list->convert = convert;
1421 sumTimespec(&list->convert, &suspended_diff);
1422 list_add_head(&convertHead, &list->node);
1423 /* breakpoint just before sleep */
1424 list = calloc(1, sizeof(struct conversionList));
1425 list_init(&list->node);
1426 list->time = time;
1427 list->convert = convert;
1428 list_add_head(&convertHead, &list->node);
1429 }
1430 }
1431
1432 /* Find the breakpoint in the conversion list */
1433 list = node_to_item(list_head(&convertHead), struct conversionList, node);
1434 next = NULL;
1435 list_for_each(node, &convertHead) {
1436 next = node_to_item(node, struct conversionList, node);
1437 if (entry->tv_sec < next->time.tv_sec) {
1438 break;
1439 } else if (entry->tv_sec == next->time.tv_sec) {
1440 if (entry->tv_nsec < next->time.tv_nsec) {
1441 break;
1442 }
1443 }
1444 list = next;
1445 }
1446
1447 /* blend time from one breakpoint to the next */
1448 convert = list->convert;
1449 if (next) {
1450 unsigned long long total, run;
1451
1452 total = nsecTimespec(subTimespec(&time, &next->time, &list->time));
1453 time.tv_sec = entry->tv_sec;
1454 time.tv_nsec = entry->tv_nsec;
1455 run = nsecTimespec(subTimespec(&time, &time, &list->time));
1456 if (run < total) {
1457 long long crun;
1458
1459 float f = nsecTimespec(subTimespec(&time, &next->convert, &convert));
1460 f *= run;
1461 f /= total;
1462 crun = f;
1463 convert.tv_sec += crun / (long long)NS_PER_SEC;
1464 if (crun < 0) {
1465 convert.tv_nsec -= (-crun) % NS_PER_SEC;
1466 if (convert.tv_nsec < 0) {
1467 convert.tv_nsec += NS_PER_SEC;
1468 convert.tv_sec -= 1;
1469 }
1470 } else {
1471 convert.tv_nsec += crun % NS_PER_SEC;
1472 if (convert.tv_nsec >= (long)NS_PER_SEC) {
1473 convert.tv_nsec -= NS_PER_SEC;
1474 convert.tv_sec += 1;
1475 }
1476 }
1477 }
1478 }
1479
1480 /* Apply the correction factor */
1481 result->tv_sec = entry->tv_sec;
1482 result->tv_nsec = entry->tv_nsec;
1483 subTimespec(result, result, &convert);
1484}
1485
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -07001486/**
1487 * Formats a log message into a buffer
1488 *
1489 * Uses defaultBuffer if it can, otherwise malloc()'s a new buffer
1490 * If return value != defaultBuffer, caller must call free()
1491 * Returns NULL on malloc error
1492 */
1493
Mark Salyzynbe1d3c22016-03-10 08:25:33 -08001494LIBLOG_ABI_PUBLIC char *android_log_formatLogLine (
1495 AndroidLogFormat *p_format,
1496 char *defaultBuffer,
1497 size_t defaultBufferSize,
1498 const AndroidLogEntry *entry,
1499 size_t *p_outLength)
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -07001500{
Yabin Cui8a985352014-11-13 10:02:08 -08001501#if !defined(_WIN32)
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -07001502 struct tm tmBuf;
1503#endif
1504 struct tm* ptm;
Mark Salyzyn9b4d7e12017-01-30 09:16:09 -08001505 /* good margin, 23+nul for msec, 26+nul for usec, 29+nul to nsec */
1506 char timeBuf[64];
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -07001507 char prefixBuf[128], suffixBuf[128];
1508 char priChar;
1509 int prefixSuffixIsHeaderFooter = 0;
Mark Salyzyn90e7af32015-12-07 16:52:42 -08001510 char *ret;
Mark Salyzyn4cbed022015-08-31 15:53:41 -07001511 time_t now;
1512 unsigned long nsec;
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -07001513
1514 priChar = filterPriToChar(entry->priority);
Pierre Zurekead88fc2010-10-17 22:39:37 +02001515 size_t prefixLen = 0, suffixLen = 0;
1516 size_t len;
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -07001517
1518 /*
1519 * Get the current date/time in pretty form
1520 *
1521 * It's often useful when examining a log with "less" to jump to
1522 * a specific point in the file by searching for the date/time stamp.
1523 * For this reason it's very annoying to have regexp meta characters
1524 * in the time stamp. Don't use forward slashes, parenthesis,
1525 * brackets, asterisks, or other special chars here.
Mark Salyzynf28f6a92015-08-31 08:01:33 -07001526 *
1527 * The caller may have affected the timezone environment, this is
1528 * expected to be sensitive to that.
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -07001529 */
Mark Salyzyn4cbed022015-08-31 15:53:41 -07001530 now = entry->tv_sec;
1531 nsec = entry->tv_nsec;
1532 if (p_format->monotonic_output) {
Mark Salyzynb6bee332015-09-08 08:56:32 -07001533 // prevent convertMonotonic from being called if logd is monotonic
Mark Salyzynba7a9a02015-12-01 15:57:25 -08001534 if (android_log_clockid() != CLOCK_MONOTONIC) {
Mark Salyzynb6bee332015-09-08 08:56:32 -07001535 struct timespec time;
1536 convertMonotonic(&time, entry);
1537 now = time.tv_sec;
1538 nsec = time.tv_nsec;
1539 }
Mark Salyzyn4cbed022015-08-31 15:53:41 -07001540 }
1541 if (now < 0) {
1542 nsec = NS_PER_SEC - nsec;
1543 }
1544 if (p_format->epoch_output || p_format->monotonic_output) {
1545 ptm = NULL;
1546 snprintf(timeBuf, sizeof(timeBuf),
1547 p_format->monotonic_output ? "%6lld" : "%19lld",
1548 (long long)now);
1549 } else {
Yabin Cui8a985352014-11-13 10:02:08 -08001550#if !defined(_WIN32)
Mark Salyzyn4cbed022015-08-31 15:53:41 -07001551 ptm = localtime_r(&now, &tmBuf);
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -07001552#else
Mark Salyzyn4cbed022015-08-31 15:53:41 -07001553 ptm = localtime(&now);
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -07001554#endif
Mark Salyzyn4cbed022015-08-31 15:53:41 -07001555 strftime(timeBuf, sizeof(timeBuf),
1556 &"%Y-%m-%d %H:%M:%S"[p_format->year_output ? 0 : 3],
1557 ptm);
1558 }
Mark Salyzyne1f20042015-05-06 08:40:40 -07001559 len = strlen(timeBuf);
Mark Salyzyn9b4d7e12017-01-30 09:16:09 -08001560 if (p_format->nsec_time_output) {
1561 len += snprintf(timeBuf + len, sizeof(timeBuf) - len,
1562 ".%09ld", nsec);
1563 } else if (p_format->usec_time_output) {
Mark Salyzynf28f6a92015-08-31 08:01:33 -07001564 len += snprintf(timeBuf + len, sizeof(timeBuf) - len,
Mark Salyzyn4cbed022015-08-31 15:53:41 -07001565 ".%06ld", nsec / US_PER_NSEC);
Mark Salyzyne1f20042015-05-06 08:40:40 -07001566 } else {
Mark Salyzynf28f6a92015-08-31 08:01:33 -07001567 len += snprintf(timeBuf + len, sizeof(timeBuf) - len,
Mark Salyzyn4cbed022015-08-31 15:53:41 -07001568 ".%03ld", nsec / MS_PER_NSEC);
Mark Salyzynf28f6a92015-08-31 08:01:33 -07001569 }
Mark Salyzyn4cbed022015-08-31 15:53:41 -07001570 if (p_format->zone_output && ptm) {
Mark Salyzynf28f6a92015-08-31 08:01:33 -07001571 strftime(timeBuf + len, sizeof(timeBuf) - len, " %z", ptm);
Mark Salyzyne1f20042015-05-06 08:40:40 -07001572 }
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -07001573
1574 /*
1575 * Construct a buffer containing the log header and log message.
1576 */
Pierre Zurekead88fc2010-10-17 22:39:37 +02001577 if (p_format->colored_output) {
1578 prefixLen = snprintf(prefixBuf, sizeof(prefixBuf), "\x1B[38;5;%dm",
1579 colorFromPri(entry->priority));
1580 prefixLen = MIN(prefixLen, sizeof(prefixBuf));
1581 suffixLen = snprintf(suffixBuf, sizeof(suffixBuf), "\x1B[0m");
1582 suffixLen = MIN(suffixLen, sizeof(suffixBuf));
1583 }
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -07001584
Mark Salyzyn90e7af32015-12-07 16:52:42 -08001585 char uid[16];
1586 uid[0] = '\0';
1587 if (p_format->uid_output) {
1588 if (entry->uid >= 0) {
Mark Salyzyn2aa510e2015-12-08 09:15:06 -08001589
William Roberts8a5b9ca2016-04-08 12:13:17 -07001590 /*
1591 * This code is Android specific, bionic guarantees that
1592 * calls to non-reentrant getpwuid() are thread safe.
1593 */
1594#ifndef __BIONIC__
1595#warning "This code assumes that getpwuid is thread safe, only true with Bionic!"
1596#endif
1597 struct passwd* pwd = getpwuid(entry->uid);
1598 if (pwd && (strlen(pwd->pw_name) <= 5)) {
1599 snprintf(uid, sizeof(uid), "%5s:", pwd->pw_name);
Mark Salyzyn2aa510e2015-12-08 09:15:06 -08001600 } else {
1601 // Not worth parsing package list, names all longer than 5
1602 snprintf(uid, sizeof(uid), "%5d:", entry->uid);
1603 }
Mark Salyzyn90e7af32015-12-07 16:52:42 -08001604 } else {
1605 snprintf(uid, sizeof(uid), " ");
1606 }
1607 }
1608
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -07001609 switch (p_format->format) {
1610 case FORMAT_TAG:
Pierre Zurekead88fc2010-10-17 22:39:37 +02001611 len = snprintf(prefixBuf + prefixLen, sizeof(prefixBuf) - prefixLen,
Mark Salyzyn807e40e2016-09-22 09:56:51 -07001612 "%c/%-8.*s: ", priChar, (int)entry->tagLen, entry->tag);
Pierre Zurekead88fc2010-10-17 22:39:37 +02001613 strcpy(suffixBuf + suffixLen, "\n");
1614 ++suffixLen;
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -07001615 break;
1616 case FORMAT_PROCESS:
Pierre Zurekead88fc2010-10-17 22:39:37 +02001617 len = snprintf(suffixBuf + suffixLen, sizeof(suffixBuf) - suffixLen,
Mark Salyzyn807e40e2016-09-22 09:56:51 -07001618 " (%.*s)\n", (int)entry->tagLen, entry->tag);
Pierre Zurekead88fc2010-10-17 22:39:37 +02001619 suffixLen += MIN(len, sizeof(suffixBuf) - suffixLen);
1620 len = snprintf(prefixBuf + prefixLen, sizeof(prefixBuf) - prefixLen,
Mark Salyzyn90e7af32015-12-07 16:52:42 -08001621 "%c(%s%5d) ", priChar, uid, entry->pid);
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -07001622 break;
1623 case FORMAT_THREAD:
Pierre Zurekead88fc2010-10-17 22:39:37 +02001624 len = snprintf(prefixBuf + prefixLen, sizeof(prefixBuf) - prefixLen,
Mark Salyzyn90e7af32015-12-07 16:52:42 -08001625 "%c(%s%5d:%5d) ", priChar, uid, entry->pid, entry->tid);
Pierre Zurekead88fc2010-10-17 22:39:37 +02001626 strcpy(suffixBuf + suffixLen, "\n");
1627 ++suffixLen;
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -07001628 break;
1629 case FORMAT_RAW:
Pierre Zurekead88fc2010-10-17 22:39:37 +02001630 prefixBuf[prefixLen] = 0;
1631 len = 0;
1632 strcpy(suffixBuf + suffixLen, "\n");
1633 ++suffixLen;
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -07001634 break;
1635 case FORMAT_TIME:
Pierre Zurekead88fc2010-10-17 22:39:37 +02001636 len = snprintf(prefixBuf + prefixLen, sizeof(prefixBuf) - prefixLen,
Mark Salyzyn807e40e2016-09-22 09:56:51 -07001637 "%s %c/%-8.*s(%s%5d): ", timeBuf, priChar,
1638 (int)entry->tagLen, entry->tag, uid, entry->pid);
Pierre Zurekead88fc2010-10-17 22:39:37 +02001639 strcpy(suffixBuf + suffixLen, "\n");
1640 ++suffixLen;
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -07001641 break;
1642 case FORMAT_THREADTIME:
Mark Salyzyn90e7af32015-12-07 16:52:42 -08001643 ret = strchr(uid, ':');
1644 if (ret) {
1645 *ret = ' ';
1646 }
Pierre Zurekead88fc2010-10-17 22:39:37 +02001647 len = snprintf(prefixBuf + prefixLen, sizeof(prefixBuf) - prefixLen,
Mark Salyzyn807e40e2016-09-22 09:56:51 -07001648 "%s %s%5d %5d %c %-8.*s: ", timeBuf, uid, entry->pid,
1649 entry->tid, priChar, (int)entry->tagLen, entry->tag);
Pierre Zurekead88fc2010-10-17 22:39:37 +02001650 strcpy(suffixBuf + suffixLen, "\n");
1651 ++suffixLen;
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -07001652 break;
1653 case FORMAT_LONG:
Pierre Zurekead88fc2010-10-17 22:39:37 +02001654 len = snprintf(prefixBuf + prefixLen, sizeof(prefixBuf) - prefixLen,
Mark Salyzyn807e40e2016-09-22 09:56:51 -07001655 "[ %s %s%5d:%5d %c/%-8.*s ]\n",
1656 timeBuf, uid, entry->pid, entry->tid, priChar,
1657 (int)entry->tagLen, entry->tag);
Pierre Zurekead88fc2010-10-17 22:39:37 +02001658 strcpy(suffixBuf + suffixLen, "\n\n");
1659 suffixLen += 2;
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -07001660 prefixSuffixIsHeaderFooter = 1;
1661 break;
1662 case FORMAT_BRIEF:
1663 default:
Pierre Zurekead88fc2010-10-17 22:39:37 +02001664 len = snprintf(prefixBuf + prefixLen, sizeof(prefixBuf) - prefixLen,
Mark Salyzyn807e40e2016-09-22 09:56:51 -07001665 "%c/%-8.*s(%s%5d): ", priChar, (int)entry->tagLen, entry->tag,
1666 uid, entry->pid);
Pierre Zurekead88fc2010-10-17 22:39:37 +02001667 strcpy(suffixBuf + suffixLen, "\n");
1668 ++suffixLen;
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -07001669 break;
1670 }
Pierre Zurekead88fc2010-10-17 22:39:37 +02001671
Keith Prestonb45b5c92010-02-11 15:12:53 -06001672 /* snprintf has a weird return value. It returns what would have been
1673 * written given a large enough buffer. In the case that the prefix is
1674 * longer then our buffer(128), it messes up the calculations below
1675 * possibly causing heap corruption. To avoid this we double check and
1676 * set the length at the maximum (size minus null byte)
1677 */
Mark Salyzyn2f83d672016-03-11 12:06:12 -08001678 prefixLen += len;
1679 if (prefixLen >= sizeof(prefixBuf)) {
1680 prefixLen = sizeof(prefixBuf) - 1;
1681 prefixBuf[sizeof(prefixBuf) - 1] = '\0';
1682 }
1683 if (suffixLen >= sizeof(suffixBuf)) {
1684 suffixLen = sizeof(suffixBuf) - 1;
1685 suffixBuf[sizeof(suffixBuf) - 2] = '\n';
1686 suffixBuf[sizeof(suffixBuf) - 1] = '\0';
1687 }
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -07001688
1689 /* the following code is tragically unreadable */
1690
1691 size_t numLines;
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -07001692 char *p;
1693 size_t bufferSize;
1694 const char *pm;
1695
1696 if (prefixSuffixIsHeaderFooter) {
Mark Salyzynb932b2f2015-05-15 09:01:58 -07001697 /* we're just wrapping message with a header/footer */
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -07001698 numLines = 1;
1699 } else {
1700 pm = entry->message;
1701 numLines = 0;
1702
Mark Salyzynb932b2f2015-05-15 09:01:58 -07001703 /*
1704 * The line-end finding here must match the line-end finding
1705 * in for ( ... numLines...) loop below
1706 */
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -07001707 while (pm < (entry->message + entry->messageLen)) {
1708 if (*pm++ == '\n') numLines++;
1709 }
Mark Salyzynb932b2f2015-05-15 09:01:58 -07001710 /* plus one line for anything not newline-terminated at the end */
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -07001711 if (pm > entry->message && *(pm-1) != '\n') numLines++;
1712 }
1713
Mark Salyzynb932b2f2015-05-15 09:01:58 -07001714 /*
1715 * this is an upper bound--newlines in message may be counted
1716 * extraneously
1717 */
1718 bufferSize = (numLines * (prefixLen + suffixLen)) + 1;
1719 if (p_format->printable_output) {
1720 /* Calculate extra length to convert non-printable to printable */
1721 bufferSize += convertPrintable(NULL, entry->message, entry->messageLen);
1722 } else {
1723 bufferSize += entry->messageLen;
1724 }
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -07001725
1726 if (defaultBufferSize >= bufferSize) {
1727 ret = defaultBuffer;
1728 } else {
1729 ret = (char *)malloc(bufferSize);
1730
1731 if (ret == NULL) {
1732 return ret;
1733 }
1734 }
1735
1736 ret[0] = '\0'; /* to start strcat off */
1737
1738 p = ret;
1739 pm = entry->message;
1740
1741 if (prefixSuffixIsHeaderFooter) {
1742 strcat(p, prefixBuf);
1743 p += prefixLen;
Mark Salyzynb932b2f2015-05-15 09:01:58 -07001744 if (p_format->printable_output) {
1745 p += convertPrintable(p, entry->message, entry->messageLen);
1746 } else {
1747 strncat(p, entry->message, entry->messageLen);
1748 p += entry->messageLen;
1749 }
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -07001750 strcat(p, suffixBuf);
1751 p += suffixLen;
1752 } else {
Mark Salyzyn7cc80132016-01-20 13:52:46 -08001753 do {
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -07001754 const char *lineStart;
1755 size_t lineLen;
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -07001756 lineStart = pm;
1757
Mark Salyzynb932b2f2015-05-15 09:01:58 -07001758 /* Find the next end-of-line in message */
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -07001759 while (pm < (entry->message + entry->messageLen)
1760 && *pm != '\n') pm++;
1761 lineLen = pm - lineStart;
1762
1763 strcat(p, prefixBuf);
1764 p += prefixLen;
Mark Salyzynb932b2f2015-05-15 09:01:58 -07001765 if (p_format->printable_output) {
1766 p += convertPrintable(p, lineStart, lineLen);
1767 } else {
1768 strncat(p, lineStart, lineLen);
1769 p += lineLen;
1770 }
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -07001771 strcat(p, suffixBuf);
1772 p += suffixLen;
1773
1774 if (*pm == '\n') pm++;
Mark Salyzyn7cc80132016-01-20 13:52:46 -08001775 } while (pm < (entry->message + entry->messageLen));
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -07001776 }
1777
1778 if (p_outLength != NULL) {
1779 *p_outLength = p - ret;
1780 }
1781
1782 return ret;
1783}
1784
1785/**
1786 * Either print or do not print log line, based on filter
1787 *
1788 * Returns count bytes written
1789 */
1790
Mark Salyzynbe1d3c22016-03-10 08:25:33 -08001791LIBLOG_ABI_PUBLIC int android_log_printLogLine(
1792 AndroidLogFormat *p_format,
1793 int fd,
1794 const AndroidLogEntry *entry)
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -07001795{
1796 int ret;
1797 char defaultBuffer[512];
1798 char *outBuffer = NULL;
1799 size_t totalLen;
1800
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -07001801 outBuffer = android_log_formatLogLine(p_format, defaultBuffer,
1802 sizeof(defaultBuffer), entry, &totalLen);
1803
Mark Salyzyn1a57ae32016-11-11 14:41:30 -08001804 if (!outBuffer) return -1;
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -07001805
1806 do {
1807 ret = write(fd, outBuffer, totalLen);
1808 } while (ret < 0 && errno == EINTR);
1809
1810 if (ret < 0) {
1811 fprintf(stderr, "+++ LOG: write failed (errno=%d)\n", errno);
1812 ret = 0;
1813 goto done;
1814 }
1815
1816 if (((size_t)ret) < totalLen) {
1817 fprintf(stderr, "+++ LOG: write partial (%d of %d)\n", ret,
1818 (int)totalLen);
1819 goto done;
1820 }
1821
1822done:
1823 if (outBuffer != defaultBuffer) {
1824 free(outBuffer);
1825 }
1826
1827 return ret;
1828}