blob: fb942a1a5217f4c4fc8dc8ea7eb6b95c3142012b [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
635 if (eventDataLen < 1)
636 return -1;
637 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
732 if (eventDataLen < 4)
733 return -1;
Mark Salyzyn8470dad2015-03-06 20:42:57 +0000734 ival = get4LE(eventData);
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -0700735 eventData += 4;
736 eventDataLen -= 4;
737
Mark Salyzyn4fd05072016-10-18 11:30:11 -0700738 lval = ival;
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -0700739 }
Mark Salyzyn4fd05072016-10-18 11:30:11 -0700740 goto pr_lval;
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -0700741 case EVENT_TYPE_LONG:
742 /* 64-bit signed long */
Mark Salyzyn4fd05072016-10-18 11:30:11 -0700743 if (eventDataLen < 8)
744 return -1;
745 lval = get8LE(eventData);
746 eventData += 8;
747 eventDataLen -= 8;
748 pr_lval:
749 outCount = snprintf(outBuf, outBufLen, "%" PRId64, lval);
750 if (outCount < outBufLen) {
751 outBuf += outCount;
752 outBufLen -= outCount;
753 } else {
754 /* halt output */
755 goto no_room;
Jeff Brown44193d92015-04-28 12:47:02 -0700756 }
757 break;
758 case EVENT_TYPE_FLOAT:
759 /* float */
760 {
761 uint32_t ival;
762 float fval;
763
764 if (eventDataLen < 4)
765 return -1;
766 ival = get4LE(eventData);
767 fval = *(float*)&ival;
768 eventData += 4;
769 eventDataLen -= 4;
770
771 outCount = snprintf(outBuf, outBufLen, "%f", fval);
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -0700772 if (outCount < outBufLen) {
773 outBuf += outCount;
774 outBufLen -= outCount;
775 } else {
776 /* halt output */
777 goto no_room;
778 }
779 }
780 break;
781 case EVENT_TYPE_STRING:
782 /* UTF-8 chars, not NULL-terminated */
783 {
784 unsigned int strLen;
785
786 if (eventDataLen < 4)
787 return -1;
Mark Salyzyn8470dad2015-03-06 20:42:57 +0000788 strLen = get4LE(eventData);
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -0700789 eventData += 4;
790 eventDataLen -= 4;
791
792 if (eventDataLen < strLen)
793 return -1;
794
Mark Salyzyn4fd05072016-10-18 11:30:11 -0700795 if (cp && (strLen == 0)) {
796 /* reset the format if no content */
797 outBuf = outBufSave;
798 outBufLen = outBufLenSave;
799 }
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -0700800 if (strLen < outBufLen) {
801 memcpy(outBuf, eventData, strLen);
802 outBuf += strLen;
803 outBufLen -= strLen;
804 } else if (outBufLen > 0) {
805 /* copy what we can */
806 memcpy(outBuf, eventData, outBufLen);
807 outBuf += outBufLen;
808 outBufLen -= outBufLen;
809 goto no_room;
810 }
811 eventData += strLen;
812 eventDataLen -= strLen;
813 break;
814 }
815 case EVENT_TYPE_LIST:
816 /* N items, all different types */
817 {
818 unsigned char count;
819 int i;
820
821 if (eventDataLen < 1)
822 return -1;
823
824 count = *eventData++;
825 eventDataLen--;
826
827 if (outBufLen > 0) {
828 *outBuf++ = '[';
829 outBufLen--;
830 } else {
831 goto no_room;
832 }
833
834 for (i = 0; i < count; i++) {
835 result = android_log_printBinaryEvent(&eventData, &eventDataLen,
Mark Salyzyn4fd05072016-10-18 11:30:11 -0700836 &outBuf, &outBufLen, fmtStr, fmtLen);
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -0700837 if (result != 0)
838 goto bail;
839
840 if (i < count-1) {
841 if (outBufLen > 0) {
842 *outBuf++ = ',';
843 outBufLen--;
844 } else {
845 goto no_room;
846 }
847 }
848 }
849
850 if (outBufLen > 0) {
851 *outBuf++ = ']';
852 outBufLen--;
853 } else {
854 goto no_room;
855 }
856 }
857 break;
858 default:
859 fprintf(stderr, "Unknown binary event type %d\n", type);
860 return -1;
861 }
Mark Salyzyn4fd05072016-10-18 11:30:11 -0700862 if (cp && len) {
863 if (findChar(&cp, &len, '|') && findChar(&cp, &len, INT_MAX)) {
864 switch (*cp) {
865 case TYPE_OBJECTS:
866 outCount = 0;
867 /* outCount = snprintf(outBuf, outBufLen, " objects"); */
868 break;
869 case TYPE_BYTES:
870 if ((lval != 0) && ((lval % 1024) == 0)) {
871 /* repaint with multiplier */
872 static const char suffixTable[] = { 'K', 'M', 'G', 'T' };
873 size_t idx = 0;
874 outBuf -= outCount;
875 outBufLen += outCount;
876 do {
877 lval /= 1024;
878 if ((lval % 1024) != 0) break;
879 } while (++idx < ((sizeof(suffixTable) /
880 sizeof(suffixTable[0])) - 1));
881 outCount = snprintf(outBuf, outBufLen,
882 "%" PRId64 "%cB",
883 lval, suffixTable[idx]);
884 } else {
885 outCount = snprintf(outBuf, outBufLen, "B");
886 }
887 break;
888 case TYPE_MILLISECONDS:
889 if (((lval <= -1000) || (1000 <= lval)) &&
890 (outBufLen || (outBuf[-1] == '0'))) {
891 /* repaint as (fractional) seconds, possibly saving space */
892 if (outBufLen) outBuf[0] = outBuf[-1];
893 outBuf[-1] = outBuf[-2];
894 outBuf[-2] = outBuf[-3];
895 outBuf[-3] = '.';
896 while ((outBufLen == 0) || (*outBuf == '0')) {
897 --outBuf;
898 ++outBufLen;
899 }
900 if (*outBuf != '.') {
901 ++outBuf;
902 --outBufLen;
903 }
904 outCount = snprintf(outBuf, outBufLen, "s");
905 } else {
906 outCount = snprintf(outBuf, outBufLen, "ms");
907 }
908 break;
909 case TYPE_ALLOCATIONS:
910 outCount = 0;
911 /* outCount = snprintf(outBuf, outBufLen, " allocations"); */
912 break;
913 case TYPE_ID:
914 outCount = 0;
915 break;
916 case TYPE_PERCENT:
917 outCount = snprintf(outBuf, outBufLen, "%%");
918 break;
919 default: /* ? */
920 outCount = 0;
921 break;
922 }
923 ++cp;
924 --len;
925 if (outCount < outBufLen) {
926 outBuf += outCount;
927 outBufLen -= outCount;
928 } else if (outCount) {
929 /* halt output */
930 goto no_room;
931 }
932 }
933 if (!findChar(&cp, &len, ')')) len = 0;
934 if (!findChar(&cp, &len, ',')) len = 0;
935 }
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -0700936
937bail:
938 *pEventData = eventData;
939 *pEventDataLen = eventDataLen;
940 *pOutBuf = outBuf;
941 *pOutBufLen = outBufLen;
Mark Salyzyn4fd05072016-10-18 11:30:11 -0700942 if (cp) {
943 *fmtStr = cp;
944 *fmtLen = len;
945 }
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -0700946 return result;
947
948no_room:
949 result = 1;
950 goto bail;
951}
952
953/**
954 * Convert a binary log entry to ASCII form.
955 *
956 * For convenience we mimic the processLogBuffer API. There is no
957 * pre-defined output length for the binary data, since we're free to format
958 * it however we choose, which means we can't really use a fixed-size buffer
959 * here.
960 */
Mark Salyzynbe1d3c22016-03-10 08:25:33 -0800961LIBLOG_ABI_PUBLIC int android_log_processBinaryLogBuffer(
962 struct logger_entry *buf,
963 AndroidLogEntry *entry,
964 const EventTagMap *map,
965 char *messageBuf, int messageBufLen)
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -0700966{
967 size_t inCount;
Mark Salyzyn4fd05072016-10-18 11:30:11 -0700968 uint32_t tagIndex;
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -0700969 const unsigned char* eventData;
970
971 entry->tv_sec = buf->sec;
972 entry->tv_nsec = buf->nsec;
973 entry->priority = ANDROID_LOG_INFO;
Mark Salyzyn90e7af32015-12-07 16:52:42 -0800974 entry->uid = -1;
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -0700975 entry->pid = buf->pid;
976 entry->tid = buf->tid;
977
978 /*
Mark Salyzyn7bc80232015-12-11 12:32:53 -0800979 * Pull the tag out, fill in some additional details based on incoming
980 * buffer version (v3 adds lid, v4 adds uid).
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -0700981 */
982 eventData = (const unsigned char*) buf->msg;
Mark Salyzyn40b21552013-12-18 12:59:01 -0800983 struct logger_entry_v2 *buf2 = (struct logger_entry_v2 *)buf;
984 if (buf2->hdr_size) {
Mark Salyzyn305374c2016-08-18 14:59:41 -0700985 if ((buf2->hdr_size < sizeof(((struct log_msg *)NULL)->entry_v1)) ||
986 (buf2->hdr_size > sizeof(((struct log_msg *)NULL)->entry))) {
987 fprintf(stderr, "+++ LOG: entry illegal hdr_size\n");
988 return -1;
989 }
Mark Salyzyn40b21552013-12-18 12:59:01 -0800990 eventData = ((unsigned char *)buf2) + buf2->hdr_size;
Mark Salyzyn7bc80232015-12-11 12:32:53 -0800991 if ((buf2->hdr_size >= sizeof(struct logger_entry_v3)) &&
992 (((struct logger_entry_v3 *)buf)->lid == LOG_ID_SECURITY)) {
993 entry->priority = ANDROID_LOG_WARN;
994 }
Mark Salyzyn90e7af32015-12-07 16:52:42 -0800995 if (buf2->hdr_size >= sizeof(struct logger_entry_v4)) {
996 entry->uid = ((struct logger_entry_v4 *)buf)->uid;
997 }
Mark Salyzyn40b21552013-12-18 12:59:01 -0800998 }
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -0700999 inCount = buf->len;
1000 if (inCount < 4)
1001 return -1;
Mark Salyzyn8470dad2015-03-06 20:42:57 +00001002 tagIndex = get4LE(eventData);
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -07001003 eventData += 4;
1004 inCount -= 4;
1005
Mark Salyzyn807e40e2016-09-22 09:56:51 -07001006 entry->tagLen = 0;
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -07001007 if (map != NULL) {
Mark Salyzyn807e40e2016-09-22 09:56:51 -07001008 entry->tag = android_lookupEventTag_len(map, &entry->tagLen, tagIndex);
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -07001009 } else {
1010 entry->tag = NULL;
1011 }
1012
1013 /*
1014 * If we don't have a map, or didn't find the tag number in the map,
1015 * stuff a generated tag value into the start of the output buffer and
1016 * shift the buffer pointers down.
1017 */
1018 if (entry->tag == NULL) {
Mark Salyzyn807e40e2016-09-22 09:56:51 -07001019 size_t tagLen;
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -07001020
Mark Salyzyn4fd05072016-10-18 11:30:11 -07001021 tagLen = snprintf(messageBuf, messageBufLen, "[%" PRIu32 "]", tagIndex);
Mark Salyzyn807e40e2016-09-22 09:56:51 -07001022 if (tagLen >= (size_t)messageBufLen) {
1023 tagLen = messageBufLen - 1;
1024 }
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -07001025 entry->tag = messageBuf;
Mark Salyzyn807e40e2016-09-22 09:56:51 -07001026 entry->tagLen = tagLen;
1027 messageBuf += tagLen + 1;
1028 messageBufLen -= tagLen + 1;
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -07001029 }
1030
1031 /*
1032 * Format the event log data into the buffer.
1033 */
1034 char* outBuf = messageBuf;
Mark Salyzyn4fd05072016-10-18 11:30:11 -07001035 size_t outRemaining = messageBufLen - 1; /* leave one for nul byte */
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -07001036 int result;
Mark Salyzyn4fd05072016-10-18 11:30:11 -07001037 const char* fmtStr = NULL;
1038 size_t fmtLen = 0;
1039 if (descriptive_output && map) {
1040 fmtStr = android_lookupEventFormat_len(map, &fmtLen, tagIndex);
1041 }
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -07001042 result = android_log_printBinaryEvent(&eventData, &inCount, &outBuf,
Mark Salyzyn4fd05072016-10-18 11:30:11 -07001043 &outRemaining, &fmtStr, &fmtLen);
1044 if ((result == 1) && fmtStr) {
1045 /* We overflowed :-(, let's repaint the line w/o format dressings */
1046 eventData = (const unsigned char*)buf->msg;
1047 if (buf2->hdr_size) {
1048 eventData = ((unsigned char *)buf2) + buf2->hdr_size;
1049 }
1050 eventData += 4;
1051 outBuf = messageBuf;
1052 outRemaining = messageBufLen - 1;
1053 result = android_log_printBinaryEvent(&eventData, &inCount, &outBuf,
1054 &outRemaining, NULL, NULL);
1055 }
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -07001056 if (result < 0) {
1057 fprintf(stderr, "Binary log entry conversion failed\n");
1058 return -1;
1059 } else if (result == 1) {
1060 if (outBuf > messageBuf) {
1061 /* leave an indicator */
1062 *(outBuf-1) = '!';
1063 } else {
1064 /* no room to output anything at all */
1065 *outBuf++ = '!';
1066 outRemaining--;
1067 }
1068 /* pretend we ate all the data */
1069 inCount = 0;
1070 }
1071
1072 /* eat the silly terminating '\n' */
1073 if (inCount == 1 && *eventData == '\n') {
1074 eventData++;
1075 inCount--;
1076 }
1077
1078 if (inCount != 0) {
1079 fprintf(stderr,
Andrew Hsiehd2c8f522012-02-27 16:48:18 -08001080 "Warning: leftover binary log data (%zu bytes)\n", inCount);
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -07001081 }
1082
1083 /*
1084 * Terminate the buffer. The NUL byte does not count as part of
1085 * entry->messageLen.
1086 */
1087 *outBuf = '\0';
1088 entry->messageLen = outBuf - messageBuf;
1089 assert(entry->messageLen == (messageBufLen-1) - outRemaining);
1090
1091 entry->message = messageBuf;
1092
1093 return 0;
1094}
1095
Mark Salyzynb932b2f2015-05-15 09:01:58 -07001096/*
1097 * One utf8 character at a time
1098 *
1099 * Returns the length of the utf8 character in the buffer,
1100 * or -1 if illegal or truncated
1101 *
1102 * Open coded from libutils/Unicode.cpp, borrowed from utf8_length(),
1103 * can not remove from here because of library circular dependencies.
1104 * Expect one-day utf8_character_length with the same signature could
1105 * _also_ be part of libutils/Unicode.cpp if its usefullness needs to
1106 * propagate globally.
1107 */
Mark Salyzynbe1d3c22016-03-10 08:25:33 -08001108LIBLOG_WEAK ssize_t utf8_character_length(const char *src, size_t len)
Mark Salyzynb932b2f2015-05-15 09:01:58 -07001109{
1110 const char *cur = src;
1111 const char first_char = *cur++;
1112 static const uint32_t kUnicodeMaxCodepoint = 0x0010FFFF;
1113 int32_t mask, to_ignore_mask;
1114 size_t num_to_read;
1115 uint32_t utf32;
1116
1117 if ((first_char & 0x80) == 0) { /* ASCII */
Mark Salyzynfaa92e92015-09-08 07:57:27 -07001118 return first_char ? 1 : -1;
Mark Salyzynb932b2f2015-05-15 09:01:58 -07001119 }
1120
1121 /*
1122 * (UTF-8's character must not be like 10xxxxxx,
1123 * but 110xxxxx, 1110xxxx, ... or 1111110x)
1124 */
1125 if ((first_char & 0x40) == 0) {
1126 return -1;
1127 }
1128
1129 for (utf32 = 1, num_to_read = 1, mask = 0x40, to_ignore_mask = 0x80;
1130 num_to_read < 5 && (first_char & mask);
1131 num_to_read++, to_ignore_mask |= mask, mask >>= 1) {
1132 if (num_to_read > len) {
1133 return -1;
1134 }
1135 if ((*cur & 0xC0) != 0x80) { /* can not be 10xxxxxx? */
1136 return -1;
1137 }
1138 utf32 = (utf32 << 6) + (*cur++ & 0b00111111);
1139 }
1140 /* "first_char" must be (110xxxxx - 11110xxx) */
1141 if (num_to_read >= 5) {
1142 return -1;
1143 }
1144 to_ignore_mask |= mask;
1145 utf32 |= ((~to_ignore_mask) & first_char) << (6 * (num_to_read - 1));
1146 if (utf32 > kUnicodeMaxCodepoint) {
1147 return -1;
1148 }
1149 return num_to_read;
1150}
1151
1152/*
1153 * Convert to printable from message to p buffer, return string length. If p is
1154 * NULL, do not copy, but still return the expected string length.
1155 */
1156static size_t convertPrintable(char *p, const char *message, size_t messageLen)
1157{
1158 char *begin = p;
1159 bool print = p != NULL;
1160
1161 while (messageLen) {
1162 char buf[6];
1163 ssize_t len = sizeof(buf) - 1;
1164 if ((size_t)len > messageLen) {
1165 len = messageLen;
1166 }
1167 len = utf8_character_length(message, len);
1168
1169 if (len < 0) {
1170 snprintf(buf, sizeof(buf),
1171 ((messageLen > 1) && isdigit(message[1]))
1172 ? "\\%03o"
1173 : "\\%o",
1174 *message & 0377);
1175 len = 1;
1176 } else {
1177 buf[0] = '\0';
1178 if (len == 1) {
1179 if (*message == '\a') {
1180 strcpy(buf, "\\a");
1181 } else if (*message == '\b') {
1182 strcpy(buf, "\\b");
1183 } else if (*message == '\t') {
Mark Salyzyn65d5ca22015-11-18 09:58:00 -08001184 strcpy(buf, "\t"); // Do not escape tabs
Mark Salyzynb932b2f2015-05-15 09:01:58 -07001185 } else if (*message == '\v') {
1186 strcpy(buf, "\\v");
1187 } else if (*message == '\f') {
1188 strcpy(buf, "\\f");
1189 } else if (*message == '\r') {
1190 strcpy(buf, "\\r");
1191 } else if (*message == '\\') {
1192 strcpy(buf, "\\\\");
1193 } else if ((*message < ' ') || (*message & 0x80)) {
1194 snprintf(buf, sizeof(buf), "\\%o", *message & 0377);
1195 }
1196 }
1197 if (!buf[0]) {
1198 strncpy(buf, message, len);
1199 buf[len] = '\0';
1200 }
1201 }
1202 if (print) {
1203 strcpy(p, buf);
1204 }
1205 p += strlen(buf);
1206 message += len;
1207 messageLen -= len;
1208 }
1209 return p - begin;
1210}
1211
Mark Salyzynbe1d3c22016-03-10 08:25:33 -08001212static char *readSeconds(char *e, struct timespec *t)
Mark Salyzyn4cbed022015-08-31 15:53:41 -07001213{
1214 unsigned long multiplier;
1215 char *p;
1216 t->tv_sec = strtoul(e, &p, 10);
1217 if (*p != '.') {
1218 return NULL;
1219 }
1220 t->tv_nsec = 0;
1221 multiplier = NS_PER_SEC;
1222 while (isdigit(*++p) && (multiplier /= 10)) {
1223 t->tv_nsec += (*p - '0') * multiplier;
1224 }
1225 return p;
1226}
1227
1228static struct timespec *sumTimespec(struct timespec *left,
1229 struct timespec *right)
1230{
1231 left->tv_nsec += right->tv_nsec;
1232 left->tv_sec += right->tv_sec;
1233 if (left->tv_nsec >= (long)NS_PER_SEC) {
1234 left->tv_nsec -= NS_PER_SEC;
1235 left->tv_sec += 1;
1236 }
1237 return left;
1238}
1239
1240static struct timespec *subTimespec(struct timespec *result,
1241 struct timespec *left,
1242 struct timespec *right)
1243{
1244 result->tv_nsec = left->tv_nsec - right->tv_nsec;
1245 result->tv_sec = left->tv_sec - right->tv_sec;
1246 if (result->tv_nsec < 0) {
1247 result->tv_nsec += NS_PER_SEC;
1248 result->tv_sec -= 1;
1249 }
1250 return result;
1251}
1252
1253static long long nsecTimespec(struct timespec *now)
1254{
1255 return (long long)now->tv_sec * NS_PER_SEC + now->tv_nsec;
1256}
1257
1258static void convertMonotonic(struct timespec *result,
1259 const AndroidLogEntry *entry)
1260{
1261 struct listnode *node;
1262 struct conversionList {
1263 struct listnode node; /* first */
1264 struct timespec time;
1265 struct timespec convert;
1266 } *list, *next;
1267 struct timespec time, convert;
1268
1269 /* If we do not have a conversion list, build one up */
1270 if (list_empty(&convertHead)) {
1271 bool suspended_pending = false;
1272 struct timespec suspended_monotonic = { 0, 0 };
1273 struct timespec suspended_diff = { 0, 0 };
1274
1275 /*
1276 * Read dmesg for _some_ synchronization markers and insert
1277 * Anything in the Android Logger before the dmesg logging span will
1278 * be highly suspect regarding the monotonic time calculations.
1279 */
Mark Salyzyn78786da2016-04-28 16:06:24 -07001280 FILE *p = popen("/system/bin/dmesg", "re");
Mark Salyzyn4cbed022015-08-31 15:53:41 -07001281 if (p) {
1282 char *line = NULL;
1283 size_t len = 0;
1284 while (getline(&line, &len, p) > 0) {
1285 static const char suspend[] = "PM: suspend entry ";
1286 static const char resume[] = "PM: suspend exit ";
1287 static const char healthd[] = "healthd";
1288 static const char battery[] = ": battery ";
1289 static const char suspended[] = "Suspended for ";
1290 struct timespec monotonic;
1291 struct tm tm;
1292 char *cp, *e = line;
1293 bool add_entry = true;
1294
1295 if (*e == '<') {
1296 while (*e && (*e != '>')) {
1297 ++e;
1298 }
1299 if (*e != '>') {
1300 continue;
1301 }
1302 }
1303 if (*e != '[') {
1304 continue;
1305 }
1306 while (*++e == ' ') {
1307 ;
1308 }
1309 e = readSeconds(e, &monotonic);
1310 if (!e || (*e != ']')) {
1311 continue;
1312 }
1313
1314 if ((e = strstr(e, suspend))) {
1315 e += sizeof(suspend) - 1;
1316 } else if ((e = strstr(line, resume))) {
1317 e += sizeof(resume) - 1;
1318 } else if (((e = strstr(line, healthd)))
1319 && ((e = strstr(e + sizeof(healthd) - 1, battery)))) {
1320 /* NB: healthd is roughly 150us late, worth the price to
1321 * deal with ntp-induced or hardware clock drift. */
1322 e += sizeof(battery) - 1;
1323 } else if ((e = strstr(line, suspended))) {
1324 e += sizeof(suspended) - 1;
1325 e = readSeconds(e, &time);
1326 if (!e) {
1327 continue;
1328 }
1329 add_entry = false;
1330 suspended_pending = true;
1331 suspended_monotonic = monotonic;
1332 suspended_diff = time;
1333 } else {
1334 continue;
1335 }
1336 if (add_entry) {
1337 /* look for "????-??-?? ??:??:??.????????? UTC" */
1338 cp = strstr(e, " UTC");
1339 if (!cp || ((cp - e) < 29) || (cp[-10] != '.')) {
1340 continue;
1341 }
1342 e = cp - 29;
1343 cp = readSeconds(cp - 10, &time);
1344 if (!cp) {
1345 continue;
1346 }
1347 cp = strptime(e, "%Y-%m-%d %H:%M:%S.", &tm);
1348 if (!cp) {
1349 continue;
1350 }
1351 cp = getenv(tz);
1352 if (cp) {
1353 cp = strdup(cp);
1354 }
1355 setenv(tz, utc, 1);
1356 time.tv_sec = mktime(&tm);
1357 if (cp) {
1358 setenv(tz, cp, 1);
1359 free(cp);
1360 } else {
1361 unsetenv(tz);
1362 }
1363 list = calloc(1, sizeof(struct conversionList));
1364 list_init(&list->node);
1365 list->time = time;
1366 subTimespec(&list->convert, &time, &monotonic);
1367 list_add_tail(&convertHead, &list->node);
1368 }
1369 if (suspended_pending && !list_empty(&convertHead)) {
1370 list = node_to_item(list_tail(&convertHead),
1371 struct conversionList, node);
1372 if (subTimespec(&time,
1373 subTimespec(&time,
1374 &list->time,
1375 &list->convert),
1376 &suspended_monotonic)->tv_sec > 0) {
1377 /* resume, what is convert factor before? */
1378 subTimespec(&convert, &list->convert, &suspended_diff);
1379 } else {
1380 /* suspend */
1381 convert = list->convert;
1382 }
1383 time = suspended_monotonic;
1384 sumTimespec(&time, &convert);
1385 /* breakpoint just before sleep */
1386 list = calloc(1, sizeof(struct conversionList));
1387 list_init(&list->node);
1388 list->time = time;
1389 list->convert = convert;
1390 list_add_tail(&convertHead, &list->node);
1391 /* breakpoint just after sleep */
1392 list = calloc(1, sizeof(struct conversionList));
1393 list_init(&list->node);
1394 list->time = time;
1395 sumTimespec(&list->time, &suspended_diff);
1396 list->convert = convert;
1397 sumTimespec(&list->convert, &suspended_diff);
1398 list_add_tail(&convertHead, &list->node);
1399 suspended_pending = false;
1400 }
1401 }
1402 pclose(p);
1403 }
1404 /* last entry is our current time conversion */
1405 list = calloc(1, sizeof(struct conversionList));
1406 list_init(&list->node);
1407 clock_gettime(CLOCK_REALTIME, &list->time);
1408 clock_gettime(CLOCK_MONOTONIC, &convert);
1409 clock_gettime(CLOCK_MONOTONIC, &time);
1410 /* Correct for instant clock_gettime latency (syscall or ~30ns) */
1411 subTimespec(&time, &convert, subTimespec(&time, &time, &convert));
1412 /* Calculate conversion factor */
1413 subTimespec(&list->convert, &list->time, &time);
1414 list_add_tail(&convertHead, &list->node);
1415 if (suspended_pending) {
1416 /* manufacture a suspend @ point before */
1417 subTimespec(&convert, &list->convert, &suspended_diff);
1418 time = suspended_monotonic;
1419 sumTimespec(&time, &convert);
1420 /* breakpoint just after sleep */
1421 list = calloc(1, sizeof(struct conversionList));
1422 list_init(&list->node);
1423 list->time = time;
1424 sumTimespec(&list->time, &suspended_diff);
1425 list->convert = convert;
1426 sumTimespec(&list->convert, &suspended_diff);
1427 list_add_head(&convertHead, &list->node);
1428 /* breakpoint just before sleep */
1429 list = calloc(1, sizeof(struct conversionList));
1430 list_init(&list->node);
1431 list->time = time;
1432 list->convert = convert;
1433 list_add_head(&convertHead, &list->node);
1434 }
1435 }
1436
1437 /* Find the breakpoint in the conversion list */
1438 list = node_to_item(list_head(&convertHead), struct conversionList, node);
1439 next = NULL;
1440 list_for_each(node, &convertHead) {
1441 next = node_to_item(node, struct conversionList, node);
1442 if (entry->tv_sec < next->time.tv_sec) {
1443 break;
1444 } else if (entry->tv_sec == next->time.tv_sec) {
1445 if (entry->tv_nsec < next->time.tv_nsec) {
1446 break;
1447 }
1448 }
1449 list = next;
1450 }
1451
1452 /* blend time from one breakpoint to the next */
1453 convert = list->convert;
1454 if (next) {
1455 unsigned long long total, run;
1456
1457 total = nsecTimespec(subTimespec(&time, &next->time, &list->time));
1458 time.tv_sec = entry->tv_sec;
1459 time.tv_nsec = entry->tv_nsec;
1460 run = nsecTimespec(subTimespec(&time, &time, &list->time));
1461 if (run < total) {
1462 long long crun;
1463
1464 float f = nsecTimespec(subTimespec(&time, &next->convert, &convert));
1465 f *= run;
1466 f /= total;
1467 crun = f;
1468 convert.tv_sec += crun / (long long)NS_PER_SEC;
1469 if (crun < 0) {
1470 convert.tv_nsec -= (-crun) % NS_PER_SEC;
1471 if (convert.tv_nsec < 0) {
1472 convert.tv_nsec += NS_PER_SEC;
1473 convert.tv_sec -= 1;
1474 }
1475 } else {
1476 convert.tv_nsec += crun % NS_PER_SEC;
1477 if (convert.tv_nsec >= (long)NS_PER_SEC) {
1478 convert.tv_nsec -= NS_PER_SEC;
1479 convert.tv_sec += 1;
1480 }
1481 }
1482 }
1483 }
1484
1485 /* Apply the correction factor */
1486 result->tv_sec = entry->tv_sec;
1487 result->tv_nsec = entry->tv_nsec;
1488 subTimespec(result, result, &convert);
1489}
1490
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -07001491/**
1492 * Formats a log message into a buffer
1493 *
1494 * Uses defaultBuffer if it can, otherwise malloc()'s a new buffer
1495 * If return value != defaultBuffer, caller must call free()
1496 * Returns NULL on malloc error
1497 */
1498
Mark Salyzynbe1d3c22016-03-10 08:25:33 -08001499LIBLOG_ABI_PUBLIC char *android_log_formatLogLine (
1500 AndroidLogFormat *p_format,
1501 char *defaultBuffer,
1502 size_t defaultBufferSize,
1503 const AndroidLogEntry *entry,
1504 size_t *p_outLength)
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -07001505{
Yabin Cui8a985352014-11-13 10:02:08 -08001506#if !defined(_WIN32)
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -07001507 struct tm tmBuf;
1508#endif
1509 struct tm* ptm;
Mark Salyzynf28f6a92015-08-31 08:01:33 -07001510 char timeBuf[64]; /* good margin, 23+nul for msec, 26+nul for usec */
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -07001511 char prefixBuf[128], suffixBuf[128];
1512 char priChar;
1513 int prefixSuffixIsHeaderFooter = 0;
Mark Salyzyn90e7af32015-12-07 16:52:42 -08001514 char *ret;
Mark Salyzyn4cbed022015-08-31 15:53:41 -07001515 time_t now;
1516 unsigned long nsec;
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -07001517
1518 priChar = filterPriToChar(entry->priority);
Pierre Zurekead88fc2010-10-17 22:39:37 +02001519 size_t prefixLen = 0, suffixLen = 0;
1520 size_t len;
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -07001521
1522 /*
1523 * Get the current date/time in pretty form
1524 *
1525 * It's often useful when examining a log with "less" to jump to
1526 * a specific point in the file by searching for the date/time stamp.
1527 * For this reason it's very annoying to have regexp meta characters
1528 * in the time stamp. Don't use forward slashes, parenthesis,
1529 * brackets, asterisks, or other special chars here.
Mark Salyzynf28f6a92015-08-31 08:01:33 -07001530 *
1531 * The caller may have affected the timezone environment, this is
1532 * expected to be sensitive to that.
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -07001533 */
Mark Salyzyn4cbed022015-08-31 15:53:41 -07001534 now = entry->tv_sec;
1535 nsec = entry->tv_nsec;
1536 if (p_format->monotonic_output) {
Mark Salyzynb6bee332015-09-08 08:56:32 -07001537 // prevent convertMonotonic from being called if logd is monotonic
Mark Salyzynba7a9a02015-12-01 15:57:25 -08001538 if (android_log_clockid() != CLOCK_MONOTONIC) {
Mark Salyzynb6bee332015-09-08 08:56:32 -07001539 struct timespec time;
1540 convertMonotonic(&time, entry);
1541 now = time.tv_sec;
1542 nsec = time.tv_nsec;
1543 }
Mark Salyzyn4cbed022015-08-31 15:53:41 -07001544 }
1545 if (now < 0) {
1546 nsec = NS_PER_SEC - nsec;
1547 }
1548 if (p_format->epoch_output || p_format->monotonic_output) {
1549 ptm = NULL;
1550 snprintf(timeBuf, sizeof(timeBuf),
1551 p_format->monotonic_output ? "%6lld" : "%19lld",
1552 (long long)now);
1553 } else {
Yabin Cui8a985352014-11-13 10:02:08 -08001554#if !defined(_WIN32)
Mark Salyzyn4cbed022015-08-31 15:53:41 -07001555 ptm = localtime_r(&now, &tmBuf);
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -07001556#else
Mark Salyzyn4cbed022015-08-31 15:53:41 -07001557 ptm = localtime(&now);
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -07001558#endif
Mark Salyzyn4cbed022015-08-31 15:53:41 -07001559 strftime(timeBuf, sizeof(timeBuf),
1560 &"%Y-%m-%d %H:%M:%S"[p_format->year_output ? 0 : 3],
1561 ptm);
1562 }
Mark Salyzyne1f20042015-05-06 08:40:40 -07001563 len = strlen(timeBuf);
1564 if (p_format->usec_time_output) {
Mark Salyzynf28f6a92015-08-31 08:01:33 -07001565 len += snprintf(timeBuf + len, sizeof(timeBuf) - len,
Mark Salyzyn4cbed022015-08-31 15:53:41 -07001566 ".%06ld", nsec / US_PER_NSEC);
Mark Salyzyne1f20042015-05-06 08:40:40 -07001567 } else {
Mark Salyzynf28f6a92015-08-31 08:01:33 -07001568 len += snprintf(timeBuf + len, sizeof(timeBuf) - len,
Mark Salyzyn4cbed022015-08-31 15:53:41 -07001569 ".%03ld", nsec / MS_PER_NSEC);
Mark Salyzynf28f6a92015-08-31 08:01:33 -07001570 }
Mark Salyzyn4cbed022015-08-31 15:53:41 -07001571 if (p_format->zone_output && ptm) {
Mark Salyzynf28f6a92015-08-31 08:01:33 -07001572 strftime(timeBuf + len, sizeof(timeBuf) - len, " %z", ptm);
Mark Salyzyne1f20042015-05-06 08:40:40 -07001573 }
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -07001574
1575 /*
1576 * Construct a buffer containing the log header and log message.
1577 */
Pierre Zurekead88fc2010-10-17 22:39:37 +02001578 if (p_format->colored_output) {
1579 prefixLen = snprintf(prefixBuf, sizeof(prefixBuf), "\x1B[38;5;%dm",
1580 colorFromPri(entry->priority));
1581 prefixLen = MIN(prefixLen, sizeof(prefixBuf));
1582 suffixLen = snprintf(suffixBuf, sizeof(suffixBuf), "\x1B[0m");
1583 suffixLen = MIN(suffixLen, sizeof(suffixBuf));
1584 }
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -07001585
Mark Salyzyn90e7af32015-12-07 16:52:42 -08001586 char uid[16];
1587 uid[0] = '\0';
1588 if (p_format->uid_output) {
1589 if (entry->uid >= 0) {
Mark Salyzyn2aa510e2015-12-08 09:15:06 -08001590
William Roberts8a5b9ca2016-04-08 12:13:17 -07001591 /*
1592 * This code is Android specific, bionic guarantees that
1593 * calls to non-reentrant getpwuid() are thread safe.
1594 */
1595#ifndef __BIONIC__
1596#warning "This code assumes that getpwuid is thread safe, only true with Bionic!"
1597#endif
1598 struct passwd* pwd = getpwuid(entry->uid);
1599 if (pwd && (strlen(pwd->pw_name) <= 5)) {
1600 snprintf(uid, sizeof(uid), "%5s:", pwd->pw_name);
Mark Salyzyn2aa510e2015-12-08 09:15:06 -08001601 } else {
1602 // Not worth parsing package list, names all longer than 5
1603 snprintf(uid, sizeof(uid), "%5d:", entry->uid);
1604 }
Mark Salyzyn90e7af32015-12-07 16:52:42 -08001605 } else {
1606 snprintf(uid, sizeof(uid), " ");
1607 }
1608 }
1609
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -07001610 switch (p_format->format) {
1611 case FORMAT_TAG:
Pierre Zurekead88fc2010-10-17 22:39:37 +02001612 len = snprintf(prefixBuf + prefixLen, sizeof(prefixBuf) - prefixLen,
Mark Salyzyn807e40e2016-09-22 09:56:51 -07001613 "%c/%-8.*s: ", priChar, (int)entry->tagLen, entry->tag);
Pierre Zurekead88fc2010-10-17 22:39:37 +02001614 strcpy(suffixBuf + suffixLen, "\n");
1615 ++suffixLen;
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -07001616 break;
1617 case FORMAT_PROCESS:
Pierre Zurekead88fc2010-10-17 22:39:37 +02001618 len = snprintf(suffixBuf + suffixLen, sizeof(suffixBuf) - suffixLen,
Mark Salyzyn807e40e2016-09-22 09:56:51 -07001619 " (%.*s)\n", (int)entry->tagLen, entry->tag);
Pierre Zurekead88fc2010-10-17 22:39:37 +02001620 suffixLen += MIN(len, sizeof(suffixBuf) - suffixLen);
1621 len = snprintf(prefixBuf + prefixLen, sizeof(prefixBuf) - prefixLen,
Mark Salyzyn90e7af32015-12-07 16:52:42 -08001622 "%c(%s%5d) ", priChar, uid, entry->pid);
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -07001623 break;
1624 case FORMAT_THREAD:
Pierre Zurekead88fc2010-10-17 22:39:37 +02001625 len = snprintf(prefixBuf + prefixLen, sizeof(prefixBuf) - prefixLen,
Mark Salyzyn90e7af32015-12-07 16:52:42 -08001626 "%c(%s%5d:%5d) ", priChar, uid, entry->pid, entry->tid);
Pierre Zurekead88fc2010-10-17 22:39:37 +02001627 strcpy(suffixBuf + suffixLen, "\n");
1628 ++suffixLen;
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -07001629 break;
1630 case FORMAT_RAW:
Pierre Zurekead88fc2010-10-17 22:39:37 +02001631 prefixBuf[prefixLen] = 0;
1632 len = 0;
1633 strcpy(suffixBuf + suffixLen, "\n");
1634 ++suffixLen;
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -07001635 break;
1636 case FORMAT_TIME:
Pierre Zurekead88fc2010-10-17 22:39:37 +02001637 len = snprintf(prefixBuf + prefixLen, sizeof(prefixBuf) - prefixLen,
Mark Salyzyn807e40e2016-09-22 09:56:51 -07001638 "%s %c/%-8.*s(%s%5d): ", timeBuf, priChar,
1639 (int)entry->tagLen, entry->tag, uid, entry->pid);
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_THREADTIME:
Mark Salyzyn90e7af32015-12-07 16:52:42 -08001644 ret = strchr(uid, ':');
1645 if (ret) {
1646 *ret = ' ';
1647 }
Pierre Zurekead88fc2010-10-17 22:39:37 +02001648 len = snprintf(prefixBuf + prefixLen, sizeof(prefixBuf) - prefixLen,
Mark Salyzyn807e40e2016-09-22 09:56:51 -07001649 "%s %s%5d %5d %c %-8.*s: ", timeBuf, uid, entry->pid,
1650 entry->tid, priChar, (int)entry->tagLen, entry->tag);
Pierre Zurekead88fc2010-10-17 22:39:37 +02001651 strcpy(suffixBuf + suffixLen, "\n");
1652 ++suffixLen;
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -07001653 break;
1654 case FORMAT_LONG:
Pierre Zurekead88fc2010-10-17 22:39:37 +02001655 len = snprintf(prefixBuf + prefixLen, sizeof(prefixBuf) - prefixLen,
Mark Salyzyn807e40e2016-09-22 09:56:51 -07001656 "[ %s %s%5d:%5d %c/%-8.*s ]\n",
1657 timeBuf, uid, entry->pid, entry->tid, priChar,
1658 (int)entry->tagLen, entry->tag);
Pierre Zurekead88fc2010-10-17 22:39:37 +02001659 strcpy(suffixBuf + suffixLen, "\n\n");
1660 suffixLen += 2;
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -07001661 prefixSuffixIsHeaderFooter = 1;
1662 break;
1663 case FORMAT_BRIEF:
1664 default:
Pierre Zurekead88fc2010-10-17 22:39:37 +02001665 len = snprintf(prefixBuf + prefixLen, sizeof(prefixBuf) - prefixLen,
Mark Salyzyn807e40e2016-09-22 09:56:51 -07001666 "%c/%-8.*s(%s%5d): ", priChar, (int)entry->tagLen, entry->tag,
1667 uid, entry->pid);
Pierre Zurekead88fc2010-10-17 22:39:37 +02001668 strcpy(suffixBuf + suffixLen, "\n");
1669 ++suffixLen;
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -07001670 break;
1671 }
Pierre Zurekead88fc2010-10-17 22:39:37 +02001672
Keith Prestonb45b5c92010-02-11 15:12:53 -06001673 /* snprintf has a weird return value. It returns what would have been
1674 * written given a large enough buffer. In the case that the prefix is
1675 * longer then our buffer(128), it messes up the calculations below
1676 * possibly causing heap corruption. To avoid this we double check and
1677 * set the length at the maximum (size minus null byte)
1678 */
Mark Salyzyn2f83d672016-03-11 12:06:12 -08001679 prefixLen += len;
1680 if (prefixLen >= sizeof(prefixBuf)) {
1681 prefixLen = sizeof(prefixBuf) - 1;
1682 prefixBuf[sizeof(prefixBuf) - 1] = '\0';
1683 }
1684 if (suffixLen >= sizeof(suffixBuf)) {
1685 suffixLen = sizeof(suffixBuf) - 1;
1686 suffixBuf[sizeof(suffixBuf) - 2] = '\n';
1687 suffixBuf[sizeof(suffixBuf) - 1] = '\0';
1688 }
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -07001689
1690 /* the following code is tragically unreadable */
1691
1692 size_t numLines;
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -07001693 char *p;
1694 size_t bufferSize;
1695 const char *pm;
1696
1697 if (prefixSuffixIsHeaderFooter) {
Mark Salyzynb932b2f2015-05-15 09:01:58 -07001698 /* we're just wrapping message with a header/footer */
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -07001699 numLines = 1;
1700 } else {
1701 pm = entry->message;
1702 numLines = 0;
1703
Mark Salyzynb932b2f2015-05-15 09:01:58 -07001704 /*
1705 * The line-end finding here must match the line-end finding
1706 * in for ( ... numLines...) loop below
1707 */
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -07001708 while (pm < (entry->message + entry->messageLen)) {
1709 if (*pm++ == '\n') numLines++;
1710 }
Mark Salyzynb932b2f2015-05-15 09:01:58 -07001711 /* plus one line for anything not newline-terminated at the end */
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -07001712 if (pm > entry->message && *(pm-1) != '\n') numLines++;
1713 }
1714
Mark Salyzynb932b2f2015-05-15 09:01:58 -07001715 /*
1716 * this is an upper bound--newlines in message may be counted
1717 * extraneously
1718 */
1719 bufferSize = (numLines * (prefixLen + suffixLen)) + 1;
1720 if (p_format->printable_output) {
1721 /* Calculate extra length to convert non-printable to printable */
1722 bufferSize += convertPrintable(NULL, entry->message, entry->messageLen);
1723 } else {
1724 bufferSize += entry->messageLen;
1725 }
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -07001726
1727 if (defaultBufferSize >= bufferSize) {
1728 ret = defaultBuffer;
1729 } else {
1730 ret = (char *)malloc(bufferSize);
1731
1732 if (ret == NULL) {
1733 return ret;
1734 }
1735 }
1736
1737 ret[0] = '\0'; /* to start strcat off */
1738
1739 p = ret;
1740 pm = entry->message;
1741
1742 if (prefixSuffixIsHeaderFooter) {
1743 strcat(p, prefixBuf);
1744 p += prefixLen;
Mark Salyzynb932b2f2015-05-15 09:01:58 -07001745 if (p_format->printable_output) {
1746 p += convertPrintable(p, entry->message, entry->messageLen);
1747 } else {
1748 strncat(p, entry->message, entry->messageLen);
1749 p += entry->messageLen;
1750 }
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -07001751 strcat(p, suffixBuf);
1752 p += suffixLen;
1753 } else {
Mark Salyzyn7cc80132016-01-20 13:52:46 -08001754 do {
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -07001755 const char *lineStart;
1756 size_t lineLen;
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -07001757 lineStart = pm;
1758
Mark Salyzynb932b2f2015-05-15 09:01:58 -07001759 /* Find the next end-of-line in message */
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -07001760 while (pm < (entry->message + entry->messageLen)
1761 && *pm != '\n') pm++;
1762 lineLen = pm - lineStart;
1763
1764 strcat(p, prefixBuf);
1765 p += prefixLen;
Mark Salyzynb932b2f2015-05-15 09:01:58 -07001766 if (p_format->printable_output) {
1767 p += convertPrintable(p, lineStart, lineLen);
1768 } else {
1769 strncat(p, lineStart, lineLen);
1770 p += lineLen;
1771 }
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -07001772 strcat(p, suffixBuf);
1773 p += suffixLen;
1774
1775 if (*pm == '\n') pm++;
Mark Salyzyn7cc80132016-01-20 13:52:46 -08001776 } while (pm < (entry->message + entry->messageLen));
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -07001777 }
1778
1779 if (p_outLength != NULL) {
1780 *p_outLength = p - ret;
1781 }
1782
1783 return ret;
1784}
1785
1786/**
1787 * Either print or do not print log line, based on filter
1788 *
1789 * Returns count bytes written
1790 */
1791
Mark Salyzynbe1d3c22016-03-10 08:25:33 -08001792LIBLOG_ABI_PUBLIC int android_log_printLogLine(
1793 AndroidLogFormat *p_format,
1794 int fd,
1795 const AndroidLogEntry *entry)
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -07001796{
1797 int ret;
1798 char defaultBuffer[512];
1799 char *outBuffer = NULL;
1800 size_t totalLen;
1801
The Android Open Source Project4f6e8d72008-10-21 07:00:00 -07001802 outBuffer = android_log_formatLogLine(p_format, defaultBuffer,
1803 sizeof(defaultBuffer), entry, &totalLen);
1804
1805 if (!outBuffer)
1806 return -1;
1807
1808 do {
1809 ret = write(fd, outBuffer, totalLen);
1810 } while (ret < 0 && errno == EINTR);
1811
1812 if (ret < 0) {
1813 fprintf(stderr, "+++ LOG: write failed (errno=%d)\n", errno);
1814 ret = 0;
1815 goto done;
1816 }
1817
1818 if (((size_t)ret) < totalLen) {
1819 fprintf(stderr, "+++ LOG: write partial (%d of %d)\n", ret,
1820 (int)totalLen);
1821 goto done;
1822 }
1823
1824done:
1825 if (outBuffer != defaultBuffer) {
1826 free(outBuffer);
1827 }
1828
1829 return ret;
1830}