blob: da80e36b84b4ba864a2303a9763d75a8a692851d [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 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;
Mark Salyzyn4fd05072016-10-18 11:30:11 -070061 bool descriptive_output;
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -070062};
63
Pierre Zurekead88fc2010-10-17 22:39:37 +020064/*
Mark Salyzyn4fd05072016-10-18 11:30:11 -070065 * API issues prevent us from exposing "descriptive" in AndroidLogFormat_t
66 * during android_log_processBinaryLogBuffer(), so we break layering.
67 */
68static bool descriptive_output = false;
69
70/*
Pierre Zurekead88fc2010-10-17 22:39:37 +020071 * gnome-terminal color tags
72 * See http://misc.flogisoft.com/bash/tip_colors_and_formatting
73 * for ideas on how to set the forground color of the text for xterm.
74 * The color manipulation character stream is defined as:
75 * ESC [ 3 8 ; 5 ; <color#> m
76 */
77#define ANDROID_COLOR_BLUE 75
78#define ANDROID_COLOR_DEFAULT 231
79#define ANDROID_COLOR_GREEN 40
80#define ANDROID_COLOR_ORANGE 166
81#define ANDROID_COLOR_RED 196
82#define ANDROID_COLOR_YELLOW 226
83
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -070084static FilterInfo * filterinfo_new(const char * tag, android_LogPriority pri)
85{
86 FilterInfo *p_ret;
87
88 p_ret = (FilterInfo *)calloc(1, sizeof(FilterInfo));
89 p_ret->mTag = strdup(tag);
90 p_ret->mPri = pri;
91
92 return p_ret;
93}
94
Mark Salyzyna04464a2014-04-30 08:50:53 -070095/* balance to above, filterinfo_free left unimplemented */
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -070096
97/*
98 * Note: also accepts 0-9 priorities
99 * returns ANDROID_LOG_UNKNOWN if the character is unrecognized
100 */
101static android_LogPriority filterCharToPri (char c)
102{
103 android_LogPriority pri;
104
105 c = tolower(c);
106
107 if (c >= '0' && c <= '9') {
108 if (c >= ('0'+ANDROID_LOG_SILENT)) {
109 pri = ANDROID_LOG_VERBOSE;
110 } else {
111 pri = (android_LogPriority)(c - '0');
112 }
113 } else if (c == 'v') {
114 pri = ANDROID_LOG_VERBOSE;
115 } else if (c == 'd') {
116 pri = ANDROID_LOG_DEBUG;
117 } else if (c == 'i') {
118 pri = ANDROID_LOG_INFO;
119 } else if (c == 'w') {
120 pri = ANDROID_LOG_WARN;
121 } else if (c == 'e') {
122 pri = ANDROID_LOG_ERROR;
123 } else if (c == 'f') {
124 pri = ANDROID_LOG_FATAL;
125 } else if (c == 's') {
126 pri = ANDROID_LOG_SILENT;
127 } else if (c == '*') {
128 pri = ANDROID_LOG_DEFAULT;
129 } else {
130 pri = ANDROID_LOG_UNKNOWN;
131 }
132
133 return pri;
134}
135
136static char filterPriToChar (android_LogPriority pri)
137{
138 switch (pri) {
139 case ANDROID_LOG_VERBOSE: return 'V';
140 case ANDROID_LOG_DEBUG: return 'D';
141 case ANDROID_LOG_INFO: return 'I';
142 case ANDROID_LOG_WARN: return 'W';
143 case ANDROID_LOG_ERROR: return 'E';
144 case ANDROID_LOG_FATAL: return 'F';
145 case ANDROID_LOG_SILENT: return 'S';
146
147 case ANDROID_LOG_DEFAULT:
148 case ANDROID_LOG_UNKNOWN:
149 default: return '?';
150 }
151}
152
Pierre Zurekead88fc2010-10-17 22:39:37 +0200153static int colorFromPri (android_LogPriority pri)
154{
155 switch (pri) {
156 case ANDROID_LOG_VERBOSE: return ANDROID_COLOR_DEFAULT;
157 case ANDROID_LOG_DEBUG: return ANDROID_COLOR_BLUE;
158 case ANDROID_LOG_INFO: return ANDROID_COLOR_GREEN;
159 case ANDROID_LOG_WARN: return ANDROID_COLOR_ORANGE;
160 case ANDROID_LOG_ERROR: return ANDROID_COLOR_RED;
161 case ANDROID_LOG_FATAL: return ANDROID_COLOR_RED;
162 case ANDROID_LOG_SILENT: return ANDROID_COLOR_DEFAULT;
163
164 case ANDROID_LOG_DEFAULT:
165 case ANDROID_LOG_UNKNOWN:
166 default: return ANDROID_COLOR_DEFAULT;
167 }
168}
169
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -0700170static android_LogPriority filterPriForTag(
171 AndroidLogFormat *p_format, const char *tag)
172{
173 FilterInfo *p_curFilter;
174
175 for (p_curFilter = p_format->filters
176 ; p_curFilter != NULL
177 ; p_curFilter = p_curFilter->p_next
178 ) {
179 if (0 == strcmp(tag, p_curFilter->mTag)) {
180 if (p_curFilter->mPri == ANDROID_LOG_DEFAULT) {
181 return p_format->global_pri;
182 } else {
183 return p_curFilter->mPri;
184 }
185 }
186 }
187
188 return p_format->global_pri;
189}
190
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -0700191/**
192 * returns 1 if this log line should be printed based on its priority
193 * and tag, and 0 if it should not
194 */
Mark Salyzynbe1d3c22016-03-10 08:25:33 -0800195LIBLOG_ABI_PUBLIC int android_log_shouldPrintLine (
196 AndroidLogFormat *p_format,
197 const char *tag,
198 android_LogPriority pri)
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -0700199{
200 return pri >= filterPriForTag(p_format, tag);
201}
202
Mark Salyzynbe1d3c22016-03-10 08:25:33 -0800203LIBLOG_ABI_PUBLIC AndroidLogFormat *android_log_format_new()
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -0700204{
205 AndroidLogFormat *p_ret;
206
207 p_ret = calloc(1, sizeof(AndroidLogFormat));
208
209 p_ret->global_pri = ANDROID_LOG_VERBOSE;
210 p_ret->format = FORMAT_BRIEF;
Pierre Zurekead88fc2010-10-17 22:39:37 +0200211 p_ret->colored_output = false;
Mark Salyzyne1f20042015-05-06 08:40:40 -0700212 p_ret->usec_time_output = false;
Mark Salyzynb932b2f2015-05-15 09:01:58 -0700213 p_ret->printable_output = false;
Mark Salyzynf28f6a92015-08-31 08:01:33 -0700214 p_ret->year_output = false;
215 p_ret->zone_output = false;
Mark Salyzyn4cbed022015-08-31 15:53:41 -0700216 p_ret->epoch_output = false;
Mark Salyzynba7a9a02015-12-01 15:57:25 -0800217 p_ret->monotonic_output = android_log_clockid() == CLOCK_MONOTONIC;
Mark Salyzyn90e7af32015-12-07 16:52:42 -0800218 p_ret->uid_output = false;
Mark Salyzyn4fd05072016-10-18 11:30:11 -0700219 p_ret->descriptive_output = false;
220 descriptive_output = false;
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -0700221
222 return p_ret;
223}
224
Mark Salyzyn4cbed022015-08-31 15:53:41 -0700225static list_declare(convertHead);
226
Mark Salyzynbe1d3c22016-03-10 08:25:33 -0800227LIBLOG_ABI_PUBLIC void android_log_format_free(AndroidLogFormat *p_format)
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -0700228{
229 FilterInfo *p_info, *p_info_old;
230
231 p_info = p_format->filters;
232
233 while (p_info != NULL) {
234 p_info_old = p_info;
235 p_info = p_info->p_next;
236
237 free(p_info_old);
238 }
239
240 free(p_format);
Mark Salyzyn4cbed022015-08-31 15:53:41 -0700241
242 /* Free conversion resource, can always be reconstructed */
243 while (!list_empty(&convertHead)) {
244 struct listnode *node = list_head(&convertHead);
245 list_remove(node);
246 free(node);
247 }
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -0700248}
249
Mark Salyzynbe1d3c22016-03-10 08:25:33 -0800250LIBLOG_ABI_PUBLIC int android_log_setPrintFormat(
251 AndroidLogFormat *p_format,
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -0700252 AndroidLogPrintFormat format)
253{
Mark Salyzynb932b2f2015-05-15 09:01:58 -0700254 switch (format) {
255 case FORMAT_MODIFIER_COLOR:
Pierre Zurekead88fc2010-10-17 22:39:37 +0200256 p_format->colored_output = true;
Mark Salyzyne1f20042015-05-06 08:40:40 -0700257 return 0;
Mark Salyzynb932b2f2015-05-15 09:01:58 -0700258 case FORMAT_MODIFIER_TIME_USEC:
Mark Salyzyne1f20042015-05-06 08:40:40 -0700259 p_format->usec_time_output = true;
260 return 0;
Mark Salyzynb932b2f2015-05-15 09:01:58 -0700261 case FORMAT_MODIFIER_PRINTABLE:
262 p_format->printable_output = true;
263 return 0;
Mark Salyzynf28f6a92015-08-31 08:01:33 -0700264 case FORMAT_MODIFIER_YEAR:
265 p_format->year_output = true;
266 return 0;
267 case FORMAT_MODIFIER_ZONE:
268 p_format->zone_output = !p_format->zone_output;
269 return 0;
Mark Salyzyn4cbed022015-08-31 15:53:41 -0700270 case FORMAT_MODIFIER_EPOCH:
271 p_format->epoch_output = true;
272 return 0;
273 case FORMAT_MODIFIER_MONOTONIC:
274 p_format->monotonic_output = true;
275 return 0;
Mark Salyzyn90e7af32015-12-07 16:52:42 -0800276 case FORMAT_MODIFIER_UID:
277 p_format->uid_output = true;
278 return 0;
Mark Salyzyn4fd05072016-10-18 11:30:11 -0700279 case FORMAT_MODIFIER_DESCRIPT:
280 p_format->descriptive_output = true;
281 descriptive_output = true;
282 return 0;
Mark Salyzynb932b2f2015-05-15 09:01:58 -0700283 default:
284 break;
Mark Salyzyne1f20042015-05-06 08:40:40 -0700285 }
286 p_format->format = format;
287 return 1;
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -0700288}
289
Mark Salyzynf28f6a92015-08-31 08:01:33 -0700290static const char tz[] = "TZ";
291static const char utc[] = "UTC";
292
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -0700293/**
294 * Returns FORMAT_OFF on invalid string
295 */
Mark Salyzynbe1d3c22016-03-10 08:25:33 -0800296LIBLOG_ABI_PUBLIC AndroidLogPrintFormat android_log_formatFromString(
297 const char * formatString)
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -0700298{
299 static AndroidLogPrintFormat format;
300
301 if (strcmp(formatString, "brief") == 0) format = FORMAT_BRIEF;
302 else if (strcmp(formatString, "process") == 0) format = FORMAT_PROCESS;
303 else if (strcmp(formatString, "tag") == 0) format = FORMAT_TAG;
304 else if (strcmp(formatString, "thread") == 0) format = FORMAT_THREAD;
305 else if (strcmp(formatString, "raw") == 0) format = FORMAT_RAW;
306 else if (strcmp(formatString, "time") == 0) format = FORMAT_TIME;
307 else if (strcmp(formatString, "threadtime") == 0) format = FORMAT_THREADTIME;
308 else if (strcmp(formatString, "long") == 0) format = FORMAT_LONG;
Mark Salyzyne1f20042015-05-06 08:40:40 -0700309 else if (strcmp(formatString, "color") == 0) format = FORMAT_MODIFIER_COLOR;
Mark Salyzyn4fd05072016-10-18 11:30:11 -0700310 else if (strcmp(formatString, "colour") == 0) format = FORMAT_MODIFIER_COLOR;
Mark Salyzyne1f20042015-05-06 08:40:40 -0700311 else if (strcmp(formatString, "usec") == 0) format = FORMAT_MODIFIER_TIME_USEC;
Mark Salyzynb932b2f2015-05-15 09:01:58 -0700312 else if (strcmp(formatString, "printable") == 0) format = FORMAT_MODIFIER_PRINTABLE;
Mark Salyzynf28f6a92015-08-31 08:01:33 -0700313 else if (strcmp(formatString, "year") == 0) format = FORMAT_MODIFIER_YEAR;
314 else if (strcmp(formatString, "zone") == 0) format = FORMAT_MODIFIER_ZONE;
Mark Salyzyn4cbed022015-08-31 15:53:41 -0700315 else if (strcmp(formatString, "epoch") == 0) format = FORMAT_MODIFIER_EPOCH;
316 else if (strcmp(formatString, "monotonic") == 0) format = FORMAT_MODIFIER_MONOTONIC;
Mark Salyzyn90e7af32015-12-07 16:52:42 -0800317 else if (strcmp(formatString, "uid") == 0) format = FORMAT_MODIFIER_UID;
Mark Salyzyn4fd05072016-10-18 11:30:11 -0700318 else if (strcmp(formatString, "descriptive") == 0) format = FORMAT_MODIFIER_DESCRIPT;
Mark Salyzynf28f6a92015-08-31 08:01:33 -0700319 else {
320 extern char *tzname[2];
321 static const char gmt[] = "GMT";
322 char *cp = getenv(tz);
323 if (cp) {
324 cp = strdup(cp);
325 }
326 setenv(tz, formatString, 1);
327 /*
328 * Run tzset here to determine if the timezone is legitimate. If the
329 * zone is GMT, check if that is what was asked for, if not then
330 * did not match any on the system; report an error to caller.
331 */
332 tzset();
333 if (!tzname[0]
334 || ((!strcmp(tzname[0], utc)
335 || !strcmp(tzname[0], gmt)) /* error? */
336 && strcasecmp(formatString, utc)
337 && strcasecmp(formatString, gmt))) { /* ok */
338 if (cp) {
339 setenv(tz, cp, 1);
340 } else {
341 unsetenv(tz);
342 }
343 tzset();
344 format = FORMAT_OFF;
345 } else {
346 format = FORMAT_MODIFIER_ZONE;
347 }
348 free(cp);
349 }
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -0700350
351 return format;
352}
353
354/**
355 * filterExpression: a single filter expression
356 * eg "AT:d"
357 *
358 * returns 0 on success and -1 on invalid expression
359 *
360 * Assumes single threaded execution
361 */
362
Mark Salyzynbe1d3c22016-03-10 08:25:33 -0800363LIBLOG_ABI_PUBLIC int android_log_addFilterRule(
364 AndroidLogFormat *p_format,
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -0700365 const char *filterExpression)
366{
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -0700367 size_t tagNameLength;
368 android_LogPriority pri = ANDROID_LOG_DEFAULT;
369
370 tagNameLength = strcspn(filterExpression, ":");
371
372 if (tagNameLength == 0) {
373 goto error;
374 }
375
376 if(filterExpression[tagNameLength] == ':') {
377 pri = filterCharToPri(filterExpression[tagNameLength+1]);
378
379 if (pri == ANDROID_LOG_UNKNOWN) {
380 goto error;
381 }
382 }
383
384 if(0 == strncmp("*", filterExpression, tagNameLength)) {
Mark Salyzynb932b2f2015-05-15 09:01:58 -0700385 /*
386 * This filter expression refers to the global filter
387 * The default level for this is DEBUG if the priority
388 * is unspecified
389 */
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -0700390 if (pri == ANDROID_LOG_DEFAULT) {
391 pri = ANDROID_LOG_DEBUG;
392 }
393
394 p_format->global_pri = pri;
395 } else {
Mark Salyzynb932b2f2015-05-15 09:01:58 -0700396 /*
397 * for filter expressions that don't refer to the global
398 * filter, the default is verbose if the priority is unspecified
399 */
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -0700400 if (pri == ANDROID_LOG_DEFAULT) {
401 pri = ANDROID_LOG_VERBOSE;
402 }
403
404 char *tagName;
405
Mark Salyzynb932b2f2015-05-15 09:01:58 -0700406/*
407 * Presently HAVE_STRNDUP is never defined, so the second case is always taken
408 * Darwin doesn't have strnup, everything else does
409 */
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -0700410#ifdef HAVE_STRNDUP
411 tagName = strndup(filterExpression, tagNameLength);
412#else
Mark Salyzynb932b2f2015-05-15 09:01:58 -0700413 /* a few extra bytes copied... */
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -0700414 tagName = strdup(filterExpression);
415 tagName[tagNameLength] = '\0';
416#endif /*HAVE_STRNDUP*/
417
418 FilterInfo *p_fi = filterinfo_new(tagName, pri);
419 free(tagName);
420
421 p_fi->p_next = p_format->filters;
422 p_format->filters = p_fi;
423 }
424
425 return 0;
426error:
427 return -1;
428}
429
430
431/**
432 * filterString: a comma/whitespace-separated set of filter expressions
433 *
434 * eg "AT:d *:i"
435 *
436 * returns 0 on success and -1 on invalid expression
437 *
438 * Assumes single threaded execution
439 *
440 */
441
Mark Salyzynbe1d3c22016-03-10 08:25:33 -0800442LIBLOG_ABI_PUBLIC int android_log_addFilterString(
443 AndroidLogFormat *p_format,
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -0700444 const char *filterString)
445{
446 char *filterStringCopy = strdup (filterString);
447 char *p_cur = filterStringCopy;
448 char *p_ret;
449 int err;
450
Mark Salyzynb932b2f2015-05-15 09:01:58 -0700451 /* Yes, I'm using strsep */
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -0700452 while (NULL != (p_ret = strsep(&p_cur, " \t,"))) {
Mark Salyzynb932b2f2015-05-15 09:01:58 -0700453 /* ignore whitespace-only entries */
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -0700454 if(p_ret[0] != '\0') {
455 err = android_log_addFilterRule(p_format, p_ret);
456
457 if (err < 0) {
458 goto error;
459 }
460 }
461 }
462
463 free (filterStringCopy);
464 return 0;
465error:
466 free (filterStringCopy);
467 return -1;
468}
469
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -0700470/**
471 * Splits a wire-format buffer into an AndroidLogEntry
472 * entry allocated by caller. Pointers will point directly into buf
473 *
474 * Returns 0 on success and -1 on invalid wire format (entry will be
475 * in unspecified state)
476 */
Mark Salyzynbe1d3c22016-03-10 08:25:33 -0800477LIBLOG_ABI_PUBLIC int android_log_processLogBuffer(
478 struct logger_entry *buf,
479 AndroidLogEntry *entry)
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -0700480{
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -0700481 entry->tv_sec = buf->sec;
482 entry->tv_nsec = buf->nsec;
Mark Salyzyn90e7af32015-12-07 16:52:42 -0800483 entry->uid = -1;
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -0700484 entry->pid = buf->pid;
485 entry->tid = buf->tid;
Kenny Root4bf3c022011-09-30 17:10:14 -0700486
487 /*
488 * format: <priority:1><tag:N>\0<message:N>\0
489 *
490 * tag str
Nick Kraleviche1ede152011-10-18 15:23:33 -0700491 * starts at buf->msg+1
Kenny Root4bf3c022011-09-30 17:10:14 -0700492 * msg
Nick Kraleviche1ede152011-10-18 15:23:33 -0700493 * starts at buf->msg+1+len(tag)+1
Jeff Sharkeya820a0e2011-10-26 18:40:39 -0700494 *
495 * The message may have been truncated by the kernel log driver.
496 * When that happens, we must null-terminate the message ourselves.
Kenny Root4bf3c022011-09-30 17:10:14 -0700497 */
Nick Kraleviche1ede152011-10-18 15:23:33 -0700498 if (buf->len < 3) {
Mark Salyzynb932b2f2015-05-15 09:01:58 -0700499 /*
500 * An well-formed entry must consist of at least a priority
501 * and two null characters
502 */
Nick Kraleviche1ede152011-10-18 15:23:33 -0700503 fprintf(stderr, "+++ LOG: entry too small\n");
Kenny Root4bf3c022011-09-30 17:10:14 -0700504 return -1;
505 }
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -0700506
Jeff Sharkeya820a0e2011-10-26 18:40:39 -0700507 int msgStart = -1;
508 int msgEnd = -1;
509
Nick Kraleviche1ede152011-10-18 15:23:33 -0700510 int i;
Mark Salyzyn40b21552013-12-18 12:59:01 -0800511 char *msg = buf->msg;
512 struct logger_entry_v2 *buf2 = (struct logger_entry_v2 *)buf;
513 if (buf2->hdr_size) {
Mark Salyzyn305374c2016-08-18 14:59:41 -0700514 if ((buf2->hdr_size < sizeof(((struct log_msg *)NULL)->entry_v1)) ||
515 (buf2->hdr_size > sizeof(((struct log_msg *)NULL)->entry))) {
516 fprintf(stderr, "+++ LOG: entry illegal hdr_size\n");
517 return -1;
518 }
Mark Salyzyn40b21552013-12-18 12:59:01 -0800519 msg = ((char *)buf2) + buf2->hdr_size;
Mark Salyzyn90e7af32015-12-07 16:52:42 -0800520 if (buf2->hdr_size >= sizeof(struct logger_entry_v4)) {
521 entry->uid = ((struct logger_entry_v4 *)buf)->uid;
522 }
Mark Salyzyn40b21552013-12-18 12:59:01 -0800523 }
Nick Kraleviche1ede152011-10-18 15:23:33 -0700524 for (i = 1; i < buf->len; i++) {
Mark Salyzyn40b21552013-12-18 12:59:01 -0800525 if (msg[i] == '\0') {
Jeff Sharkeya820a0e2011-10-26 18:40:39 -0700526 if (msgStart == -1) {
527 msgStart = i + 1;
528 } else {
529 msgEnd = i;
530 break;
531 }
Nick Kraleviche1ede152011-10-18 15:23:33 -0700532 }
533 }
Jeff Sharkeya820a0e2011-10-26 18:40:39 -0700534
535 if (msgStart == -1) {
Mark Salyzyn083c5342016-03-21 09:45:34 -0700536 /* +++ LOG: malformed log message, DYB */
537 for (i = 1; i < buf->len; i++) {
538 /* odd characters in tag? */
539 if ((msg[i] <= ' ') || (msg[i] == ':') || (msg[i] >= 0x7f)) {
540 msg[i] = '\0';
541 msgStart = i + 1;
542 break;
543 }
544 }
545 if (msgStart == -1) {
546 msgStart = buf->len - 1; /* All tag, no message, print truncates */
547 }
Nick Kralevich63f4a842011-10-17 10:45:03 -0700548 }
Jeff Sharkeya820a0e2011-10-26 18:40:39 -0700549 if (msgEnd == -1) {
Mark Salyzynb932b2f2015-05-15 09:01:58 -0700550 /* incoming message not null-terminated; force it */
Mark Salyzynd7bcf402015-12-04 09:24:15 -0800551 msgEnd = buf->len - 1; /* may result in msgEnd < msgStart */
Mark Salyzyn40b21552013-12-18 12:59:01 -0800552 msg[msgEnd] = '\0';
Jeff Sharkeya820a0e2011-10-26 18:40:39 -0700553 }
554
Mark Salyzyn40b21552013-12-18 12:59:01 -0800555 entry->priority = msg[0];
556 entry->tag = msg + 1;
Mark Salyzyn807e40e2016-09-22 09:56:51 -0700557 entry->tagLen = msgStart - 1;
Mark Salyzyn40b21552013-12-18 12:59:01 -0800558 entry->message = msg + msgStart;
Mark Salyzynd7bcf402015-12-04 09:24:15 -0800559 entry->messageLen = (msgEnd < msgStart) ? 0 : (msgEnd - msgStart);
Nick Kralevich63f4a842011-10-17 10:45:03 -0700560
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -0700561 return 0;
562}
563
564/*
Mark Salyzyn8470dad2015-03-06 20:42:57 +0000565 * Extract a 4-byte value from a byte stream.
566 */
567static inline uint32_t get4LE(const uint8_t* src)
568{
569 return src[0] | (src[1] << 8) | (src[2] << 16) | (src[3] << 24);
570}
571
572/*
573 * Extract an 8-byte value from a byte stream.
574 */
575static inline uint64_t get8LE(const uint8_t* src)
576{
577 uint32_t low, high;
578
579 low = src[0] | (src[1] << 8) | (src[2] << 16) | (src[3] << 24);
580 high = src[4] | (src[5] << 8) | (src[6] << 16) | (src[7] << 24);
Jeff Brown44193d92015-04-28 12:47:02 -0700581 return ((uint64_t) high << 32) | (uint64_t) low;
Mark Salyzyn8470dad2015-03-06 20:42:57 +0000582}
583
Mark Salyzyn4fd05072016-10-18 11:30:11 -0700584static bool findChar(const char** cp, size_t* len, int c) {
585 while (*len && isspace(**cp)) {
586 ++*cp;
587 --*len;
588 }
589 if (c == INT_MAX) return *len;
590 if (*len && (**cp == c)) {
591 ++*cp;
592 --*len;
593 return true;
594 }
595 return false;
596}
Mark Salyzyn8470dad2015-03-06 20:42:57 +0000597
598/*
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -0700599 * Recursively convert binary log data to printable form.
600 *
601 * This needs to be recursive because you can have lists of lists.
602 *
603 * If we run out of room, we stop processing immediately. It's important
604 * for us to check for space on every output element to avoid producing
605 * garbled output.
606 *
607 * Returns 0 on success, 1 on buffer full, -1 on failure.
608 */
Mark Salyzyn4fd05072016-10-18 11:30:11 -0700609enum objectType {
610 TYPE_OBJECTS = '1',
611 TYPE_BYTES = '2',
612 TYPE_MILLISECONDS = '3',
613 TYPE_ALLOCATIONS = '4',
614 TYPE_ID = '5',
615 TYPE_PERCENT = '6'
616};
617
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -0700618static int android_log_printBinaryEvent(const unsigned char** pEventData,
Mark Salyzyn4fd05072016-10-18 11:30:11 -0700619 size_t* pEventDataLen, char** pOutBuf, size_t* pOutBufLen,
620 const char** fmtStr, size_t* fmtLen)
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -0700621{
622 const unsigned char* eventData = *pEventData;
623 size_t eventDataLen = *pEventDataLen;
624 char* outBuf = *pOutBuf;
Mark Salyzyn4fd05072016-10-18 11:30:11 -0700625 char* outBufSave = outBuf;
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -0700626 size_t outBufLen = *pOutBufLen;
Mark Salyzyn4fd05072016-10-18 11:30:11 -0700627 size_t outBufLenSave = outBufLen;
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -0700628 unsigned char type;
629 size_t outCount;
630 int result = 0;
Mark Salyzyn4fd05072016-10-18 11:30:11 -0700631 const char* cp;
632 size_t len;
633 int64_t lval;
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -0700634
Mark Salyzyn1a57ae32016-11-11 14:41:30 -0800635 if (eventDataLen < 1) return -1;
636
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -0700637 type = *eventData++;
638 eventDataLen--;
639
Mark Salyzyn4fd05072016-10-18 11:30:11 -0700640 cp = NULL;
641 len = 0;
642 if (fmtStr && *fmtStr && fmtLen && *fmtLen && **fmtStr) {
643 cp = *fmtStr;
644 len = *fmtLen;
645 }
646 /*
647 * event.logtag format specification:
648 *
649 * Optionally, after the tag names can be put a description for the value(s)
650 * of the tag. Description are in the format
651 * (<name>|data type[|data unit])
652 * Multiple values are separated by commas.
653 *
654 * The data type is a number from the following values:
655 * 1: int
656 * 2: long
657 * 3: string
658 * 4: list
659 * 5: float
660 *
661 * The data unit is a number taken from the following list:
662 * 1: Number of objects
663 * 2: Number of bytes
664 * 3: Number of milliseconds
665 * 4: Number of allocations
666 * 5: Id
667 * 6: Percent
668 * Default value for data of type int/long is 2 (bytes).
669 */
670 if (!cp || !findChar(&cp, &len, '(')) {
671 len = 0;
672 } else {
673 char* outBufLastSpace = NULL;
674
675 findChar(&cp, &len, INT_MAX);
676 while (len && *cp && (*cp != '|') && (*cp != ')')) {
677 if (outBufLen <= 0) {
678 /* halt output */
679 goto no_room;
680 }
681 outBufLastSpace = isspace(*cp) ? outBuf : NULL;
682 *outBuf = *cp;
683 ++outBuf;
684 ++cp;
685 --outBufLen;
686 --len;
687 }
688 if (outBufLastSpace) {
689 outBufLen += outBuf - outBufLastSpace;
690 outBuf = outBufLastSpace;
691 }
692 if (outBufLen <= 0) {
693 /* halt output */
694 goto no_room;
695 }
696 if (outBufSave != outBuf) {
697 *outBuf = '=';
698 ++outBuf;
699 --outBufLen;
700 }
701
702 if (findChar(&cp, &len, '|') && findChar(&cp, &len, INT_MAX)) {
703 static const unsigned char typeTable[] = {
704 EVENT_TYPE_INT,
705 EVENT_TYPE_LONG,
706 EVENT_TYPE_STRING,
707 EVENT_TYPE_LIST,
708 EVENT_TYPE_FLOAT
709 };
710
711 if ((*cp >= '1') &&
712 (*cp < (char)('1' + (sizeof(typeTable) / sizeof(typeTable[0])))) &&
713 (type != typeTable[(size_t)(*cp - '1')])) len = 0;
714
715 if (len) {
716 ++cp;
717 --len;
718 } else {
719 /* reset the format */
720 outBuf = outBufSave;
721 outBufLen = outBufLenSave;
722 }
723 }
724 }
725 lval = 0;
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -0700726 switch (type) {
727 case EVENT_TYPE_INT:
728 /* 32-bit signed int */
729 {
Mark Salyzyn4fd05072016-10-18 11:30:11 -0700730 int32_t ival;
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -0700731
Mark Salyzyn1a57ae32016-11-11 14:41:30 -0800732 if (eventDataLen < 4) return -1;
Mark Salyzyn8470dad2015-03-06 20:42:57 +0000733 ival = get4LE(eventData);
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -0700734 eventData += 4;
735 eventDataLen -= 4;
736
Mark Salyzyn4fd05072016-10-18 11:30:11 -0700737 lval = ival;
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -0700738 }
Mark Salyzyn4fd05072016-10-18 11:30:11 -0700739 goto pr_lval;
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -0700740 case EVENT_TYPE_LONG:
741 /* 64-bit signed long */
Mark Salyzyn1a57ae32016-11-11 14:41:30 -0800742 if (eventDataLen < 8) return -1;
Mark Salyzyn4fd05072016-10-18 11:30:11 -0700743 lval = get8LE(eventData);
744 eventData += 8;
745 eventDataLen -= 8;
746 pr_lval:
747 outCount = snprintf(outBuf, outBufLen, "%" PRId64, lval);
748 if (outCount < outBufLen) {
749 outBuf += outCount;
750 outBufLen -= outCount;
751 } else {
752 /* halt output */
753 goto no_room;
Jeff Brown44193d92015-04-28 12:47:02 -0700754 }
755 break;
756 case EVENT_TYPE_FLOAT:
757 /* float */
758 {
759 uint32_t ival;
760 float fval;
761
Mark Salyzyn1a57ae32016-11-11 14:41:30 -0800762 if (eventDataLen < 4) return -1;
Jeff Brown44193d92015-04-28 12:47:02 -0700763 ival = get4LE(eventData);
764 fval = *(float*)&ival;
765 eventData += 4;
766 eventDataLen -= 4;
767
768 outCount = snprintf(outBuf, outBufLen, "%f", fval);
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -0700769 if (outCount < outBufLen) {
770 outBuf += outCount;
771 outBufLen -= outCount;
772 } else {
773 /* halt output */
774 goto no_room;
775 }
776 }
777 break;
778 case EVENT_TYPE_STRING:
779 /* UTF-8 chars, not NULL-terminated */
780 {
781 unsigned int strLen;
782
Mark Salyzyn1a57ae32016-11-11 14:41:30 -0800783 if (eventDataLen < 4) return -1;
Mark Salyzyn8470dad2015-03-06 20:42:57 +0000784 strLen = get4LE(eventData);
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -0700785 eventData += 4;
786 eventDataLen -= 4;
787
Mark Salyzyn1a57ae32016-11-11 14:41:30 -0800788 if (eventDataLen < strLen) return -1;
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -0700789
Mark Salyzyn4fd05072016-10-18 11:30:11 -0700790 if (cp && (strLen == 0)) {
791 /* reset the format if no content */
792 outBuf = outBufSave;
793 outBufLen = outBufLenSave;
794 }
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -0700795 if (strLen < outBufLen) {
796 memcpy(outBuf, eventData, strLen);
797 outBuf += strLen;
798 outBufLen -= strLen;
799 } else if (outBufLen > 0) {
800 /* copy what we can */
801 memcpy(outBuf, eventData, outBufLen);
802 outBuf += outBufLen;
803 outBufLen -= outBufLen;
804 goto no_room;
805 }
806 eventData += strLen;
807 eventDataLen -= strLen;
808 break;
809 }
810 case EVENT_TYPE_LIST:
811 /* N items, all different types */
812 {
813 unsigned char count;
814 int i;
815
Mark Salyzyn1a57ae32016-11-11 14:41:30 -0800816 if (eventDataLen < 1) return -1;
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -0700817
818 count = *eventData++;
819 eventDataLen--;
820
Mark Salyzyn1a57ae32016-11-11 14:41:30 -0800821 if (outBufLen <= 0) goto no_room;
822
823 *outBuf++ = '[';
824 outBufLen--;
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -0700825
826 for (i = 0; i < count; i++) {
827 result = android_log_printBinaryEvent(&eventData, &eventDataLen,
Mark Salyzyn4fd05072016-10-18 11:30:11 -0700828 &outBuf, &outBufLen, fmtStr, fmtLen);
Mark Salyzyn1a57ae32016-11-11 14:41:30 -0800829 if (result != 0) goto bail;
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -0700830
Mark Salyzyn1a57ae32016-11-11 14:41:30 -0800831 if (i < (count - 1)) {
832 if (outBufLen <= 0) goto no_room;
833 *outBuf++ = ',';
834 outBufLen--;
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -0700835 }
836 }
837
Mark Salyzyn1a57ae32016-11-11 14:41:30 -0800838 if (outBufLen <= 0) goto no_room;
839
840 *outBuf++ = ']';
841 outBufLen--;
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -0700842 }
843 break;
844 default:
845 fprintf(stderr, "Unknown binary event type %d\n", type);
846 return -1;
847 }
Mark Salyzyn4fd05072016-10-18 11:30:11 -0700848 if (cp && len) {
849 if (findChar(&cp, &len, '|') && findChar(&cp, &len, INT_MAX)) {
850 switch (*cp) {
851 case TYPE_OBJECTS:
852 outCount = 0;
853 /* outCount = snprintf(outBuf, outBufLen, " objects"); */
854 break;
855 case TYPE_BYTES:
856 if ((lval != 0) && ((lval % 1024) == 0)) {
857 /* repaint with multiplier */
858 static const char suffixTable[] = { 'K', 'M', 'G', 'T' };
859 size_t idx = 0;
860 outBuf -= outCount;
861 outBufLen += outCount;
862 do {
863 lval /= 1024;
864 if ((lval % 1024) != 0) break;
865 } while (++idx < ((sizeof(suffixTable) /
866 sizeof(suffixTable[0])) - 1));
867 outCount = snprintf(outBuf, outBufLen,
868 "%" PRId64 "%cB",
869 lval, suffixTable[idx]);
870 } else {
871 outCount = snprintf(outBuf, outBufLen, "B");
872 }
873 break;
874 case TYPE_MILLISECONDS:
875 if (((lval <= -1000) || (1000 <= lval)) &&
876 (outBufLen || (outBuf[-1] == '0'))) {
877 /* repaint as (fractional) seconds, possibly saving space */
878 if (outBufLen) outBuf[0] = outBuf[-1];
879 outBuf[-1] = outBuf[-2];
880 outBuf[-2] = outBuf[-3];
881 outBuf[-3] = '.';
882 while ((outBufLen == 0) || (*outBuf == '0')) {
883 --outBuf;
884 ++outBufLen;
885 }
886 if (*outBuf != '.') {
887 ++outBuf;
888 --outBufLen;
889 }
890 outCount = snprintf(outBuf, outBufLen, "s");
891 } else {
892 outCount = snprintf(outBuf, outBufLen, "ms");
893 }
894 break;
895 case TYPE_ALLOCATIONS:
896 outCount = 0;
897 /* outCount = snprintf(outBuf, outBufLen, " allocations"); */
898 break;
899 case TYPE_ID:
900 outCount = 0;
901 break;
902 case TYPE_PERCENT:
903 outCount = snprintf(outBuf, outBufLen, "%%");
904 break;
905 default: /* ? */
906 outCount = 0;
907 break;
908 }
909 ++cp;
910 --len;
911 if (outCount < outBufLen) {
912 outBuf += outCount;
913 outBufLen -= outCount;
914 } else if (outCount) {
915 /* halt output */
916 goto no_room;
917 }
918 }
919 if (!findChar(&cp, &len, ')')) len = 0;
920 if (!findChar(&cp, &len, ',')) len = 0;
921 }
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -0700922
923bail:
924 *pEventData = eventData;
925 *pEventDataLen = eventDataLen;
926 *pOutBuf = outBuf;
927 *pOutBufLen = outBufLen;
Mark Salyzyn4fd05072016-10-18 11:30:11 -0700928 if (cp) {
929 *fmtStr = cp;
930 *fmtLen = len;
931 }
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -0700932 return result;
933
934no_room:
935 result = 1;
936 goto bail;
937}
938
939/**
940 * Convert a binary log entry to ASCII form.
941 *
942 * For convenience we mimic the processLogBuffer API. There is no
943 * pre-defined output length for the binary data, since we're free to format
944 * it however we choose, which means we can't really use a fixed-size buffer
945 * here.
946 */
Mark Salyzynbe1d3c22016-03-10 08:25:33 -0800947LIBLOG_ABI_PUBLIC int android_log_processBinaryLogBuffer(
948 struct logger_entry *buf,
949 AndroidLogEntry *entry,
950 const EventTagMap *map,
951 char *messageBuf, int messageBufLen)
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -0700952{
953 size_t inCount;
Mark Salyzyn4fd05072016-10-18 11:30:11 -0700954 uint32_t tagIndex;
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -0700955 const unsigned char* eventData;
956
957 entry->tv_sec = buf->sec;
958 entry->tv_nsec = buf->nsec;
959 entry->priority = ANDROID_LOG_INFO;
Mark Salyzyn90e7af32015-12-07 16:52:42 -0800960 entry->uid = -1;
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -0700961 entry->pid = buf->pid;
962 entry->tid = buf->tid;
963
964 /*
Mark Salyzyn7bc80232015-12-11 12:32:53 -0800965 * Pull the tag out, fill in some additional details based on incoming
966 * buffer version (v3 adds lid, v4 adds uid).
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -0700967 */
968 eventData = (const unsigned char*) buf->msg;
Mark Salyzyn40b21552013-12-18 12:59:01 -0800969 struct logger_entry_v2 *buf2 = (struct logger_entry_v2 *)buf;
970 if (buf2->hdr_size) {
Mark Salyzyn305374c2016-08-18 14:59:41 -0700971 if ((buf2->hdr_size < sizeof(((struct log_msg *)NULL)->entry_v1)) ||
972 (buf2->hdr_size > sizeof(((struct log_msg *)NULL)->entry))) {
973 fprintf(stderr, "+++ LOG: entry illegal hdr_size\n");
974 return -1;
975 }
Mark Salyzyn40b21552013-12-18 12:59:01 -0800976 eventData = ((unsigned char *)buf2) + buf2->hdr_size;
Mark Salyzyn7bc80232015-12-11 12:32:53 -0800977 if ((buf2->hdr_size >= sizeof(struct logger_entry_v3)) &&
978 (((struct logger_entry_v3 *)buf)->lid == LOG_ID_SECURITY)) {
979 entry->priority = ANDROID_LOG_WARN;
980 }
Mark Salyzyn90e7af32015-12-07 16:52:42 -0800981 if (buf2->hdr_size >= sizeof(struct logger_entry_v4)) {
982 entry->uid = ((struct logger_entry_v4 *)buf)->uid;
983 }
Mark Salyzyn40b21552013-12-18 12:59:01 -0800984 }
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -0700985 inCount = buf->len;
Mark Salyzyn1a57ae32016-11-11 14:41:30 -0800986 if (inCount < 4) return -1;
Mark Salyzyn8470dad2015-03-06 20:42:57 +0000987 tagIndex = get4LE(eventData);
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -0700988 eventData += 4;
989 inCount -= 4;
990
Mark Salyzyn807e40e2016-09-22 09:56:51 -0700991 entry->tagLen = 0;
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -0700992 if (map != NULL) {
Mark Salyzyn807e40e2016-09-22 09:56:51 -0700993 entry->tag = android_lookupEventTag_len(map, &entry->tagLen, tagIndex);
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -0700994 } else {
995 entry->tag = NULL;
996 }
997
998 /*
999 * If we don't have a map, or didn't find the tag number in the map,
1000 * stuff a generated tag value into the start of the output buffer and
1001 * shift the buffer pointers down.
1002 */
1003 if (entry->tag == NULL) {
Mark Salyzyn807e40e2016-09-22 09:56:51 -07001004 size_t tagLen;
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -07001005
Mark Salyzyn4fd05072016-10-18 11:30:11 -07001006 tagLen = snprintf(messageBuf, messageBufLen, "[%" PRIu32 "]", tagIndex);
Mark Salyzyn807e40e2016-09-22 09:56:51 -07001007 if (tagLen >= (size_t)messageBufLen) {
1008 tagLen = messageBufLen - 1;
1009 }
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -07001010 entry->tag = messageBuf;
Mark Salyzyn807e40e2016-09-22 09:56:51 -07001011 entry->tagLen = tagLen;
1012 messageBuf += tagLen + 1;
1013 messageBufLen -= tagLen + 1;
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -07001014 }
1015
1016 /*
1017 * Format the event log data into the buffer.
1018 */
Mark Salyzyn4fd05072016-10-18 11:30:11 -07001019 const char* fmtStr = NULL;
1020 size_t fmtLen = 0;
1021 if (descriptive_output && map) {
1022 fmtStr = android_lookupEventFormat_len(map, &fmtLen, tagIndex);
1023 }
Mark Salyzyn1a57ae32016-11-11 14:41:30 -08001024
1025 char* outBuf = messageBuf;
1026 size_t outRemaining = messageBufLen - 1; /* leave one for nul byte */
1027 int result = 0;
1028
1029 if ((inCount > 0) || fmtLen) {
1030 result = android_log_printBinaryEvent(&eventData, &inCount, &outBuf,
1031 &outRemaining, &fmtStr, &fmtLen);
1032 }
Mark Salyzyn4fd05072016-10-18 11:30:11 -07001033 if ((result == 1) && fmtStr) {
1034 /* We overflowed :-(, let's repaint the line w/o format dressings */
1035 eventData = (const unsigned char*)buf->msg;
1036 if (buf2->hdr_size) {
1037 eventData = ((unsigned char *)buf2) + buf2->hdr_size;
1038 }
1039 eventData += 4;
1040 outBuf = messageBuf;
1041 outRemaining = messageBufLen - 1;
1042 result = android_log_printBinaryEvent(&eventData, &inCount, &outBuf,
1043 &outRemaining, NULL, NULL);
1044 }
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -07001045 if (result < 0) {
1046 fprintf(stderr, "Binary log entry conversion failed\n");
Mark Salyzyn1a57ae32016-11-11 14:41:30 -08001047 }
1048 if (result) {
1049 if (!outRemaining) {
1050 /* make space to leave an indicator */
1051 --outBuf;
1052 ++outRemaining;
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -07001053 }
Mark Salyzyn1a57ae32016-11-11 14:41:30 -08001054 *outBuf++ = (result < 0) ? '!' : '^'; /* Error or Truncation? */
1055 outRemaining--;
1056 /* pretend we ate all the data to prevent log stutter */
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -07001057 inCount = 0;
Mark Salyzyn538bc122016-11-16 15:28:31 -08001058 if (result > 0) result = 0;
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -07001059 }
1060
1061 /* eat the silly terminating '\n' */
1062 if (inCount == 1 && *eventData == '\n') {
1063 eventData++;
1064 inCount--;
1065 }
1066
1067 if (inCount != 0) {
1068 fprintf(stderr,
Andrew Hsiehd2c8f522012-02-27 16:48:18 -08001069 "Warning: leftover binary log data (%zu bytes)\n", inCount);
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -07001070 }
1071
1072 /*
1073 * Terminate the buffer. The NUL byte does not count as part of
1074 * entry->messageLen.
1075 */
1076 *outBuf = '\0';
1077 entry->messageLen = outBuf - messageBuf;
1078 assert(entry->messageLen == (messageBufLen-1) - outRemaining);
1079
1080 entry->message = messageBuf;
1081
Mark Salyzyn538bc122016-11-16 15:28:31 -08001082 return result;
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -07001083}
1084
Mark Salyzynb932b2f2015-05-15 09:01:58 -07001085/*
1086 * One utf8 character at a time
1087 *
1088 * Returns the length of the utf8 character in the buffer,
1089 * or -1 if illegal or truncated
1090 *
1091 * Open coded from libutils/Unicode.cpp, borrowed from utf8_length(),
1092 * can not remove from here because of library circular dependencies.
1093 * Expect one-day utf8_character_length with the same signature could
1094 * _also_ be part of libutils/Unicode.cpp if its usefullness needs to
1095 * propagate globally.
1096 */
Mark Salyzynbe1d3c22016-03-10 08:25:33 -08001097LIBLOG_WEAK ssize_t utf8_character_length(const char *src, size_t len)
Mark Salyzynb932b2f2015-05-15 09:01:58 -07001098{
1099 const char *cur = src;
1100 const char first_char = *cur++;
1101 static const uint32_t kUnicodeMaxCodepoint = 0x0010FFFF;
1102 int32_t mask, to_ignore_mask;
1103 size_t num_to_read;
1104 uint32_t utf32;
1105
1106 if ((first_char & 0x80) == 0) { /* ASCII */
Mark Salyzynfaa92e92015-09-08 07:57:27 -07001107 return first_char ? 1 : -1;
Mark Salyzynb932b2f2015-05-15 09:01:58 -07001108 }
1109
1110 /*
1111 * (UTF-8's character must not be like 10xxxxxx,
1112 * but 110xxxxx, 1110xxxx, ... or 1111110x)
1113 */
1114 if ((first_char & 0x40) == 0) {
1115 return -1;
1116 }
1117
1118 for (utf32 = 1, num_to_read = 1, mask = 0x40, to_ignore_mask = 0x80;
1119 num_to_read < 5 && (first_char & mask);
1120 num_to_read++, to_ignore_mask |= mask, mask >>= 1) {
1121 if (num_to_read > len) {
1122 return -1;
1123 }
1124 if ((*cur & 0xC0) != 0x80) { /* can not be 10xxxxxx? */
1125 return -1;
1126 }
1127 utf32 = (utf32 << 6) + (*cur++ & 0b00111111);
1128 }
1129 /* "first_char" must be (110xxxxx - 11110xxx) */
1130 if (num_to_read >= 5) {
1131 return -1;
1132 }
1133 to_ignore_mask |= mask;
1134 utf32 |= ((~to_ignore_mask) & first_char) << (6 * (num_to_read - 1));
1135 if (utf32 > kUnicodeMaxCodepoint) {
1136 return -1;
1137 }
1138 return num_to_read;
1139}
1140
1141/*
1142 * Convert to printable from message to p buffer, return string length. If p is
1143 * NULL, do not copy, but still return the expected string length.
1144 */
1145static size_t convertPrintable(char *p, const char *message, size_t messageLen)
1146{
1147 char *begin = p;
1148 bool print = p != NULL;
1149
1150 while (messageLen) {
1151 char buf[6];
1152 ssize_t len = sizeof(buf) - 1;
1153 if ((size_t)len > messageLen) {
1154 len = messageLen;
1155 }
1156 len = utf8_character_length(message, len);
1157
1158 if (len < 0) {
1159 snprintf(buf, sizeof(buf),
1160 ((messageLen > 1) && isdigit(message[1]))
1161 ? "\\%03o"
1162 : "\\%o",
1163 *message & 0377);
1164 len = 1;
1165 } else {
1166 buf[0] = '\0';
1167 if (len == 1) {
1168 if (*message == '\a') {
1169 strcpy(buf, "\\a");
1170 } else if (*message == '\b') {
1171 strcpy(buf, "\\b");
1172 } else if (*message == '\t') {
Mark Salyzyn65d5ca22015-11-18 09:58:00 -08001173 strcpy(buf, "\t"); // Do not escape tabs
Mark Salyzynb932b2f2015-05-15 09:01:58 -07001174 } else if (*message == '\v') {
1175 strcpy(buf, "\\v");
1176 } else if (*message == '\f') {
1177 strcpy(buf, "\\f");
1178 } else if (*message == '\r') {
1179 strcpy(buf, "\\r");
1180 } else if (*message == '\\') {
1181 strcpy(buf, "\\\\");
1182 } else if ((*message < ' ') || (*message & 0x80)) {
1183 snprintf(buf, sizeof(buf), "\\%o", *message & 0377);
1184 }
1185 }
1186 if (!buf[0]) {
1187 strncpy(buf, message, len);
1188 buf[len] = '\0';
1189 }
1190 }
1191 if (print) {
1192 strcpy(p, buf);
1193 }
1194 p += strlen(buf);
1195 message += len;
1196 messageLen -= len;
1197 }
1198 return p - begin;
1199}
1200
Mark Salyzynbe1d3c22016-03-10 08:25:33 -08001201static char *readSeconds(char *e, struct timespec *t)
Mark Salyzyn4cbed022015-08-31 15:53:41 -07001202{
1203 unsigned long multiplier;
1204 char *p;
1205 t->tv_sec = strtoul(e, &p, 10);
1206 if (*p != '.') {
1207 return NULL;
1208 }
1209 t->tv_nsec = 0;
1210 multiplier = NS_PER_SEC;
1211 while (isdigit(*++p) && (multiplier /= 10)) {
1212 t->tv_nsec += (*p - '0') * multiplier;
1213 }
1214 return p;
1215}
1216
1217static struct timespec *sumTimespec(struct timespec *left,
1218 struct timespec *right)
1219{
1220 left->tv_nsec += right->tv_nsec;
1221 left->tv_sec += right->tv_sec;
1222 if (left->tv_nsec >= (long)NS_PER_SEC) {
1223 left->tv_nsec -= NS_PER_SEC;
1224 left->tv_sec += 1;
1225 }
1226 return left;
1227}
1228
1229static struct timespec *subTimespec(struct timespec *result,
1230 struct timespec *left,
1231 struct timespec *right)
1232{
1233 result->tv_nsec = left->tv_nsec - right->tv_nsec;
1234 result->tv_sec = left->tv_sec - right->tv_sec;
1235 if (result->tv_nsec < 0) {
1236 result->tv_nsec += NS_PER_SEC;
1237 result->tv_sec -= 1;
1238 }
1239 return result;
1240}
1241
1242static long long nsecTimespec(struct timespec *now)
1243{
1244 return (long long)now->tv_sec * NS_PER_SEC + now->tv_nsec;
1245}
1246
1247static void convertMonotonic(struct timespec *result,
1248 const AndroidLogEntry *entry)
1249{
1250 struct listnode *node;
1251 struct conversionList {
1252 struct listnode node; /* first */
1253 struct timespec time;
1254 struct timespec convert;
1255 } *list, *next;
1256 struct timespec time, convert;
1257
1258 /* If we do not have a conversion list, build one up */
1259 if (list_empty(&convertHead)) {
1260 bool suspended_pending = false;
1261 struct timespec suspended_monotonic = { 0, 0 };
1262 struct timespec suspended_diff = { 0, 0 };
1263
1264 /*
1265 * Read dmesg for _some_ synchronization markers and insert
1266 * Anything in the Android Logger before the dmesg logging span will
1267 * be highly suspect regarding the monotonic time calculations.
1268 */
Mark Salyzyn78786da2016-04-28 16:06:24 -07001269 FILE *p = popen("/system/bin/dmesg", "re");
Mark Salyzyn4cbed022015-08-31 15:53:41 -07001270 if (p) {
1271 char *line = NULL;
1272 size_t len = 0;
1273 while (getline(&line, &len, p) > 0) {
1274 static const char suspend[] = "PM: suspend entry ";
1275 static const char resume[] = "PM: suspend exit ";
1276 static const char healthd[] = "healthd";
1277 static const char battery[] = ": battery ";
1278 static const char suspended[] = "Suspended for ";
1279 struct timespec monotonic;
1280 struct tm tm;
1281 char *cp, *e = line;
1282 bool add_entry = true;
1283
1284 if (*e == '<') {
1285 while (*e && (*e != '>')) {
1286 ++e;
1287 }
1288 if (*e != '>') {
1289 continue;
1290 }
1291 }
1292 if (*e != '[') {
1293 continue;
1294 }
1295 while (*++e == ' ') {
1296 ;
1297 }
1298 e = readSeconds(e, &monotonic);
1299 if (!e || (*e != ']')) {
1300 continue;
1301 }
1302
1303 if ((e = strstr(e, suspend))) {
1304 e += sizeof(suspend) - 1;
1305 } else if ((e = strstr(line, resume))) {
1306 e += sizeof(resume) - 1;
1307 } else if (((e = strstr(line, healthd)))
1308 && ((e = strstr(e + sizeof(healthd) - 1, battery)))) {
1309 /* NB: healthd is roughly 150us late, worth the price to
1310 * deal with ntp-induced or hardware clock drift. */
1311 e += sizeof(battery) - 1;
1312 } else if ((e = strstr(line, suspended))) {
1313 e += sizeof(suspended) - 1;
1314 e = readSeconds(e, &time);
1315 if (!e) {
1316 continue;
1317 }
1318 add_entry = false;
1319 suspended_pending = true;
1320 suspended_monotonic = monotonic;
1321 suspended_diff = time;
1322 } else {
1323 continue;
1324 }
1325 if (add_entry) {
1326 /* look for "????-??-?? ??:??:??.????????? UTC" */
1327 cp = strstr(e, " UTC");
1328 if (!cp || ((cp - e) < 29) || (cp[-10] != '.')) {
1329 continue;
1330 }
1331 e = cp - 29;
1332 cp = readSeconds(cp - 10, &time);
1333 if (!cp) {
1334 continue;
1335 }
1336 cp = strptime(e, "%Y-%m-%d %H:%M:%S.", &tm);
1337 if (!cp) {
1338 continue;
1339 }
1340 cp = getenv(tz);
1341 if (cp) {
1342 cp = strdup(cp);
1343 }
1344 setenv(tz, utc, 1);
1345 time.tv_sec = mktime(&tm);
1346 if (cp) {
1347 setenv(tz, cp, 1);
1348 free(cp);
1349 } else {
1350 unsetenv(tz);
1351 }
1352 list = calloc(1, sizeof(struct conversionList));
1353 list_init(&list->node);
1354 list->time = time;
1355 subTimespec(&list->convert, &time, &monotonic);
1356 list_add_tail(&convertHead, &list->node);
1357 }
1358 if (suspended_pending && !list_empty(&convertHead)) {
1359 list = node_to_item(list_tail(&convertHead),
1360 struct conversionList, node);
1361 if (subTimespec(&time,
1362 subTimespec(&time,
1363 &list->time,
1364 &list->convert),
1365 &suspended_monotonic)->tv_sec > 0) {
1366 /* resume, what is convert factor before? */
1367 subTimespec(&convert, &list->convert, &suspended_diff);
1368 } else {
1369 /* suspend */
1370 convert = list->convert;
1371 }
1372 time = suspended_monotonic;
1373 sumTimespec(&time, &convert);
1374 /* breakpoint just before sleep */
1375 list = calloc(1, sizeof(struct conversionList));
1376 list_init(&list->node);
1377 list->time = time;
1378 list->convert = convert;
1379 list_add_tail(&convertHead, &list->node);
1380 /* breakpoint just after sleep */
1381 list = calloc(1, sizeof(struct conversionList));
1382 list_init(&list->node);
1383 list->time = time;
1384 sumTimespec(&list->time, &suspended_diff);
1385 list->convert = convert;
1386 sumTimespec(&list->convert, &suspended_diff);
1387 list_add_tail(&convertHead, &list->node);
1388 suspended_pending = false;
1389 }
1390 }
1391 pclose(p);
1392 }
1393 /* last entry is our current time conversion */
1394 list = calloc(1, sizeof(struct conversionList));
1395 list_init(&list->node);
1396 clock_gettime(CLOCK_REALTIME, &list->time);
1397 clock_gettime(CLOCK_MONOTONIC, &convert);
1398 clock_gettime(CLOCK_MONOTONIC, &time);
1399 /* Correct for instant clock_gettime latency (syscall or ~30ns) */
1400 subTimespec(&time, &convert, subTimespec(&time, &time, &convert));
1401 /* Calculate conversion factor */
1402 subTimespec(&list->convert, &list->time, &time);
1403 list_add_tail(&convertHead, &list->node);
1404 if (suspended_pending) {
1405 /* manufacture a suspend @ point before */
1406 subTimespec(&convert, &list->convert, &suspended_diff);
1407 time = suspended_monotonic;
1408 sumTimespec(&time, &convert);
1409 /* breakpoint just after sleep */
1410 list = calloc(1, sizeof(struct conversionList));
1411 list_init(&list->node);
1412 list->time = time;
1413 sumTimespec(&list->time, &suspended_diff);
1414 list->convert = convert;
1415 sumTimespec(&list->convert, &suspended_diff);
1416 list_add_head(&convertHead, &list->node);
1417 /* breakpoint just before sleep */
1418 list = calloc(1, sizeof(struct conversionList));
1419 list_init(&list->node);
1420 list->time = time;
1421 list->convert = convert;
1422 list_add_head(&convertHead, &list->node);
1423 }
1424 }
1425
1426 /* Find the breakpoint in the conversion list */
1427 list = node_to_item(list_head(&convertHead), struct conversionList, node);
1428 next = NULL;
1429 list_for_each(node, &convertHead) {
1430 next = node_to_item(node, struct conversionList, node);
1431 if (entry->tv_sec < next->time.tv_sec) {
1432 break;
1433 } else if (entry->tv_sec == next->time.tv_sec) {
1434 if (entry->tv_nsec < next->time.tv_nsec) {
1435 break;
1436 }
1437 }
1438 list = next;
1439 }
1440
1441 /* blend time from one breakpoint to the next */
1442 convert = list->convert;
1443 if (next) {
1444 unsigned long long total, run;
1445
1446 total = nsecTimespec(subTimespec(&time, &next->time, &list->time));
1447 time.tv_sec = entry->tv_sec;
1448 time.tv_nsec = entry->tv_nsec;
1449 run = nsecTimespec(subTimespec(&time, &time, &list->time));
1450 if (run < total) {
1451 long long crun;
1452
1453 float f = nsecTimespec(subTimespec(&time, &next->convert, &convert));
1454 f *= run;
1455 f /= total;
1456 crun = f;
1457 convert.tv_sec += crun / (long long)NS_PER_SEC;
1458 if (crun < 0) {
1459 convert.tv_nsec -= (-crun) % NS_PER_SEC;
1460 if (convert.tv_nsec < 0) {
1461 convert.tv_nsec += NS_PER_SEC;
1462 convert.tv_sec -= 1;
1463 }
1464 } else {
1465 convert.tv_nsec += crun % NS_PER_SEC;
1466 if (convert.tv_nsec >= (long)NS_PER_SEC) {
1467 convert.tv_nsec -= NS_PER_SEC;
1468 convert.tv_sec += 1;
1469 }
1470 }
1471 }
1472 }
1473
1474 /* Apply the correction factor */
1475 result->tv_sec = entry->tv_sec;
1476 result->tv_nsec = entry->tv_nsec;
1477 subTimespec(result, result, &convert);
1478}
1479
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -07001480/**
1481 * Formats a log message into a buffer
1482 *
1483 * Uses defaultBuffer if it can, otherwise malloc()'s a new buffer
1484 * If return value != defaultBuffer, caller must call free()
1485 * Returns NULL on malloc error
1486 */
1487
Mark Salyzynbe1d3c22016-03-10 08:25:33 -08001488LIBLOG_ABI_PUBLIC char *android_log_formatLogLine (
1489 AndroidLogFormat *p_format,
1490 char *defaultBuffer,
1491 size_t defaultBufferSize,
1492 const AndroidLogEntry *entry,
1493 size_t *p_outLength)
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -07001494{
Yabin Cui8a985352014-11-13 10:02:08 -08001495#if !defined(_WIN32)
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -07001496 struct tm tmBuf;
1497#endif
1498 struct tm* ptm;
Mark Salyzynf28f6a92015-08-31 08:01:33 -07001499 char timeBuf[64]; /* good margin, 23+nul for msec, 26+nul for usec */
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -07001500 char prefixBuf[128], suffixBuf[128];
1501 char priChar;
1502 int prefixSuffixIsHeaderFooter = 0;
Mark Salyzyn90e7af32015-12-07 16:52:42 -08001503 char *ret;
Mark Salyzyn4cbed022015-08-31 15:53:41 -07001504 time_t now;
1505 unsigned long nsec;
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -07001506
1507 priChar = filterPriToChar(entry->priority);
Pierre Zurekead88fc2010-10-17 22:39:37 +02001508 size_t prefixLen = 0, suffixLen = 0;
1509 size_t len;
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -07001510
1511 /*
1512 * Get the current date/time in pretty form
1513 *
1514 * It's often useful when examining a log with "less" to jump to
1515 * a specific point in the file by searching for the date/time stamp.
1516 * For this reason it's very annoying to have regexp meta characters
1517 * in the time stamp. Don't use forward slashes, parenthesis,
1518 * brackets, asterisks, or other special chars here.
Mark Salyzynf28f6a92015-08-31 08:01:33 -07001519 *
1520 * The caller may have affected the timezone environment, this is
1521 * expected to be sensitive to that.
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -07001522 */
Mark Salyzyn4cbed022015-08-31 15:53:41 -07001523 now = entry->tv_sec;
1524 nsec = entry->tv_nsec;
1525 if (p_format->monotonic_output) {
Mark Salyzynb6bee332015-09-08 08:56:32 -07001526 // prevent convertMonotonic from being called if logd is monotonic
Mark Salyzynba7a9a02015-12-01 15:57:25 -08001527 if (android_log_clockid() != CLOCK_MONOTONIC) {
Mark Salyzynb6bee332015-09-08 08:56:32 -07001528 struct timespec time;
1529 convertMonotonic(&time, entry);
1530 now = time.tv_sec;
1531 nsec = time.tv_nsec;
1532 }
Mark Salyzyn4cbed022015-08-31 15:53:41 -07001533 }
1534 if (now < 0) {
1535 nsec = NS_PER_SEC - nsec;
1536 }
1537 if (p_format->epoch_output || p_format->monotonic_output) {
1538 ptm = NULL;
1539 snprintf(timeBuf, sizeof(timeBuf),
1540 p_format->monotonic_output ? "%6lld" : "%19lld",
1541 (long long)now);
1542 } else {
Yabin Cui8a985352014-11-13 10:02:08 -08001543#if !defined(_WIN32)
Mark Salyzyn4cbed022015-08-31 15:53:41 -07001544 ptm = localtime_r(&now, &tmBuf);
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -07001545#else
Mark Salyzyn4cbed022015-08-31 15:53:41 -07001546 ptm = localtime(&now);
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -07001547#endif
Mark Salyzyn4cbed022015-08-31 15:53:41 -07001548 strftime(timeBuf, sizeof(timeBuf),
1549 &"%Y-%m-%d %H:%M:%S"[p_format->year_output ? 0 : 3],
1550 ptm);
1551 }
Mark Salyzyne1f20042015-05-06 08:40:40 -07001552 len = strlen(timeBuf);
1553 if (p_format->usec_time_output) {
Mark Salyzynf28f6a92015-08-31 08:01:33 -07001554 len += snprintf(timeBuf + len, sizeof(timeBuf) - len,
Mark Salyzyn4cbed022015-08-31 15:53:41 -07001555 ".%06ld", nsec / US_PER_NSEC);
Mark Salyzyne1f20042015-05-06 08:40:40 -07001556 } else {
Mark Salyzynf28f6a92015-08-31 08:01:33 -07001557 len += snprintf(timeBuf + len, sizeof(timeBuf) - len,
Mark Salyzyn4cbed022015-08-31 15:53:41 -07001558 ".%03ld", nsec / MS_PER_NSEC);
Mark Salyzynf28f6a92015-08-31 08:01:33 -07001559 }
Mark Salyzyn4cbed022015-08-31 15:53:41 -07001560 if (p_format->zone_output && ptm) {
Mark Salyzynf28f6a92015-08-31 08:01:33 -07001561 strftime(timeBuf + len, sizeof(timeBuf) - len, " %z", ptm);
Mark Salyzyne1f20042015-05-06 08:40:40 -07001562 }
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -07001563
1564 /*
1565 * Construct a buffer containing the log header and log message.
1566 */
Pierre Zurekead88fc2010-10-17 22:39:37 +02001567 if (p_format->colored_output) {
1568 prefixLen = snprintf(prefixBuf, sizeof(prefixBuf), "\x1B[38;5;%dm",
1569 colorFromPri(entry->priority));
1570 prefixLen = MIN(prefixLen, sizeof(prefixBuf));
1571 suffixLen = snprintf(suffixBuf, sizeof(suffixBuf), "\x1B[0m");
1572 suffixLen = MIN(suffixLen, sizeof(suffixBuf));
1573 }
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -07001574
Mark Salyzyn90e7af32015-12-07 16:52:42 -08001575 char uid[16];
1576 uid[0] = '\0';
1577 if (p_format->uid_output) {
1578 if (entry->uid >= 0) {
Mark Salyzyn2aa510e2015-12-08 09:15:06 -08001579
William Roberts8a5b9ca2016-04-08 12:13:17 -07001580 /*
1581 * This code is Android specific, bionic guarantees that
1582 * calls to non-reentrant getpwuid() are thread safe.
1583 */
1584#ifndef __BIONIC__
1585#warning "This code assumes that getpwuid is thread safe, only true with Bionic!"
1586#endif
1587 struct passwd* pwd = getpwuid(entry->uid);
1588 if (pwd && (strlen(pwd->pw_name) <= 5)) {
1589 snprintf(uid, sizeof(uid), "%5s:", pwd->pw_name);
Mark Salyzyn2aa510e2015-12-08 09:15:06 -08001590 } else {
1591 // Not worth parsing package list, names all longer than 5
1592 snprintf(uid, sizeof(uid), "%5d:", entry->uid);
1593 }
Mark Salyzyn90e7af32015-12-07 16:52:42 -08001594 } else {
1595 snprintf(uid, sizeof(uid), " ");
1596 }
1597 }
1598
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -07001599 switch (p_format->format) {
1600 case FORMAT_TAG:
Pierre Zurekead88fc2010-10-17 22:39:37 +02001601 len = snprintf(prefixBuf + prefixLen, sizeof(prefixBuf) - prefixLen,
Mark Salyzyn807e40e2016-09-22 09:56:51 -07001602 "%c/%-8.*s: ", priChar, (int)entry->tagLen, entry->tag);
Pierre Zurekead88fc2010-10-17 22:39:37 +02001603 strcpy(suffixBuf + suffixLen, "\n");
1604 ++suffixLen;
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -07001605 break;
1606 case FORMAT_PROCESS:
Pierre Zurekead88fc2010-10-17 22:39:37 +02001607 len = snprintf(suffixBuf + suffixLen, sizeof(suffixBuf) - suffixLen,
Mark Salyzyn807e40e2016-09-22 09:56:51 -07001608 " (%.*s)\n", (int)entry->tagLen, entry->tag);
Pierre Zurekead88fc2010-10-17 22:39:37 +02001609 suffixLen += MIN(len, sizeof(suffixBuf) - suffixLen);
1610 len = snprintf(prefixBuf + prefixLen, sizeof(prefixBuf) - prefixLen,
Mark Salyzyn90e7af32015-12-07 16:52:42 -08001611 "%c(%s%5d) ", priChar, uid, entry->pid);
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -07001612 break;
1613 case FORMAT_THREAD:
Pierre Zurekead88fc2010-10-17 22:39:37 +02001614 len = snprintf(prefixBuf + prefixLen, sizeof(prefixBuf) - prefixLen,
Mark Salyzyn90e7af32015-12-07 16:52:42 -08001615 "%c(%s%5d:%5d) ", priChar, uid, entry->pid, entry->tid);
Pierre Zurekead88fc2010-10-17 22:39:37 +02001616 strcpy(suffixBuf + suffixLen, "\n");
1617 ++suffixLen;
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -07001618 break;
1619 case FORMAT_RAW:
Pierre Zurekead88fc2010-10-17 22:39:37 +02001620 prefixBuf[prefixLen] = 0;
1621 len = 0;
1622 strcpy(suffixBuf + suffixLen, "\n");
1623 ++suffixLen;
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -07001624 break;
1625 case FORMAT_TIME:
Pierre Zurekead88fc2010-10-17 22:39:37 +02001626 len = snprintf(prefixBuf + prefixLen, sizeof(prefixBuf) - prefixLen,
Mark Salyzyn807e40e2016-09-22 09:56:51 -07001627 "%s %c/%-8.*s(%s%5d): ", timeBuf, priChar,
1628 (int)entry->tagLen, entry->tag, uid, entry->pid);
Pierre Zurekead88fc2010-10-17 22:39:37 +02001629 strcpy(suffixBuf + suffixLen, "\n");
1630 ++suffixLen;
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -07001631 break;
1632 case FORMAT_THREADTIME:
Mark Salyzyn90e7af32015-12-07 16:52:42 -08001633 ret = strchr(uid, ':');
1634 if (ret) {
1635 *ret = ' ';
1636 }
Pierre Zurekead88fc2010-10-17 22:39:37 +02001637 len = snprintf(prefixBuf + prefixLen, sizeof(prefixBuf) - prefixLen,
Mark Salyzyn807e40e2016-09-22 09:56:51 -07001638 "%s %s%5d %5d %c %-8.*s: ", timeBuf, uid, entry->pid,
1639 entry->tid, priChar, (int)entry->tagLen, entry->tag);
Pierre Zurekead88fc2010-10-17 22:39:37 +02001640 strcpy(suffixBuf + suffixLen, "\n");
1641 ++suffixLen;
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -07001642 break;
1643 case FORMAT_LONG:
Pierre Zurekead88fc2010-10-17 22:39:37 +02001644 len = snprintf(prefixBuf + prefixLen, sizeof(prefixBuf) - prefixLen,
Mark Salyzyn807e40e2016-09-22 09:56:51 -07001645 "[ %s %s%5d:%5d %c/%-8.*s ]\n",
1646 timeBuf, uid, entry->pid, entry->tid, priChar,
1647 (int)entry->tagLen, entry->tag);
Pierre Zurekead88fc2010-10-17 22:39:37 +02001648 strcpy(suffixBuf + suffixLen, "\n\n");
1649 suffixLen += 2;
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -07001650 prefixSuffixIsHeaderFooter = 1;
1651 break;
1652 case FORMAT_BRIEF:
1653 default:
Pierre Zurekead88fc2010-10-17 22:39:37 +02001654 len = snprintf(prefixBuf + prefixLen, sizeof(prefixBuf) - prefixLen,
Mark Salyzyn807e40e2016-09-22 09:56:51 -07001655 "%c/%-8.*s(%s%5d): ", priChar, (int)entry->tagLen, entry->tag,
1656 uid, entry->pid);
Pierre Zurekead88fc2010-10-17 22:39:37 +02001657 strcpy(suffixBuf + suffixLen, "\n");
1658 ++suffixLen;
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -07001659 break;
1660 }
Pierre Zurekead88fc2010-10-17 22:39:37 +02001661
Keith Prestonb45b5c92010-02-11 15:12:53 -06001662 /* snprintf has a weird return value. It returns what would have been
1663 * written given a large enough buffer. In the case that the prefix is
1664 * longer then our buffer(128), it messes up the calculations below
1665 * possibly causing heap corruption. To avoid this we double check and
1666 * set the length at the maximum (size minus null byte)
1667 */
Mark Salyzyn2f83d672016-03-11 12:06:12 -08001668 prefixLen += len;
1669 if (prefixLen >= sizeof(prefixBuf)) {
1670 prefixLen = sizeof(prefixBuf) - 1;
1671 prefixBuf[sizeof(prefixBuf) - 1] = '\0';
1672 }
1673 if (suffixLen >= sizeof(suffixBuf)) {
1674 suffixLen = sizeof(suffixBuf) - 1;
1675 suffixBuf[sizeof(suffixBuf) - 2] = '\n';
1676 suffixBuf[sizeof(suffixBuf) - 1] = '\0';
1677 }
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -07001678
1679 /* the following code is tragically unreadable */
1680
1681 size_t numLines;
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -07001682 char *p;
1683 size_t bufferSize;
1684 const char *pm;
1685
1686 if (prefixSuffixIsHeaderFooter) {
Mark Salyzynb932b2f2015-05-15 09:01:58 -07001687 /* we're just wrapping message with a header/footer */
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -07001688 numLines = 1;
1689 } else {
1690 pm = entry->message;
1691 numLines = 0;
1692
Mark Salyzynb932b2f2015-05-15 09:01:58 -07001693 /*
1694 * The line-end finding here must match the line-end finding
1695 * in for ( ... numLines...) loop below
1696 */
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -07001697 while (pm < (entry->message + entry->messageLen)) {
1698 if (*pm++ == '\n') numLines++;
1699 }
Mark Salyzynb932b2f2015-05-15 09:01:58 -07001700 /* plus one line for anything not newline-terminated at the end */
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -07001701 if (pm > entry->message && *(pm-1) != '\n') numLines++;
1702 }
1703
Mark Salyzynb932b2f2015-05-15 09:01:58 -07001704 /*
1705 * this is an upper bound--newlines in message may be counted
1706 * extraneously
1707 */
1708 bufferSize = (numLines * (prefixLen + suffixLen)) + 1;
1709 if (p_format->printable_output) {
1710 /* Calculate extra length to convert non-printable to printable */
1711 bufferSize += convertPrintable(NULL, entry->message, entry->messageLen);
1712 } else {
1713 bufferSize += entry->messageLen;
1714 }
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -07001715
1716 if (defaultBufferSize >= bufferSize) {
1717 ret = defaultBuffer;
1718 } else {
1719 ret = (char *)malloc(bufferSize);
1720
1721 if (ret == NULL) {
1722 return ret;
1723 }
1724 }
1725
1726 ret[0] = '\0'; /* to start strcat off */
1727
1728 p = ret;
1729 pm = entry->message;
1730
1731 if (prefixSuffixIsHeaderFooter) {
1732 strcat(p, prefixBuf);
1733 p += prefixLen;
Mark Salyzynb932b2f2015-05-15 09:01:58 -07001734 if (p_format->printable_output) {
1735 p += convertPrintable(p, entry->message, entry->messageLen);
1736 } else {
1737 strncat(p, entry->message, entry->messageLen);
1738 p += entry->messageLen;
1739 }
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -07001740 strcat(p, suffixBuf);
1741 p += suffixLen;
1742 } else {
Mark Salyzyn7cc80132016-01-20 13:52:46 -08001743 do {
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -07001744 const char *lineStart;
1745 size_t lineLen;
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -07001746 lineStart = pm;
1747
Mark Salyzynb932b2f2015-05-15 09:01:58 -07001748 /* Find the next end-of-line in message */
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -07001749 while (pm < (entry->message + entry->messageLen)
1750 && *pm != '\n') pm++;
1751 lineLen = pm - lineStart;
1752
1753 strcat(p, prefixBuf);
1754 p += prefixLen;
Mark Salyzynb932b2f2015-05-15 09:01:58 -07001755 if (p_format->printable_output) {
1756 p += convertPrintable(p, lineStart, lineLen);
1757 } else {
1758 strncat(p, lineStart, lineLen);
1759 p += lineLen;
1760 }
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -07001761 strcat(p, suffixBuf);
1762 p += suffixLen;
1763
1764 if (*pm == '\n') pm++;
Mark Salyzyn7cc80132016-01-20 13:52:46 -08001765 } while (pm < (entry->message + entry->messageLen));
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -07001766 }
1767
1768 if (p_outLength != NULL) {
1769 *p_outLength = p - ret;
1770 }
1771
1772 return ret;
1773}
1774
1775/**
1776 * Either print or do not print log line, based on filter
1777 *
1778 * Returns count bytes written
1779 */
1780
Mark Salyzynbe1d3c22016-03-10 08:25:33 -08001781LIBLOG_ABI_PUBLIC int android_log_printLogLine(
1782 AndroidLogFormat *p_format,
1783 int fd,
1784 const AndroidLogEntry *entry)
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -07001785{
1786 int ret;
1787 char defaultBuffer[512];
1788 char *outBuffer = NULL;
1789 size_t totalLen;
1790
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -07001791 outBuffer = android_log_formatLogLine(p_format, defaultBuffer,
1792 sizeof(defaultBuffer), entry, &totalLen);
1793
Mark Salyzyn1a57ae32016-11-11 14:41:30 -08001794 if (!outBuffer) return -1;
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -07001795
1796 do {
1797 ret = write(fd, outBuffer, totalLen);
1798 } while (ret < 0 && errno == EINTR);
1799
1800 if (ret < 0) {
1801 fprintf(stderr, "+++ LOG: write failed (errno=%d)\n", errno);
1802 ret = 0;
1803 goto done;
1804 }
1805
1806 if (((size_t)ret) < totalLen) {
1807 fprintf(stderr, "+++ LOG: write partial (%d of %d)\n", ret,
1808 (int)totalLen);
1809 goto done;
1810 }
1811
1812done:
1813 if (outBuffer != defaultBuffer) {
1814 free(outBuffer);
1815 }
1816
1817 return ret;
1818}