async_safe_log.cpp revision 854556c41e20c37b210498b0374415b640104785
1/*
2 * Copyright (C) 2010 The Android Open Source Project
3 * All rights reserved.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
7 * are met:
8 *  * Redistributions of source code must retain the above copyright
9 *    notice, this list of conditions and the following disclaimer.
10 *  * Redistributions in binary form must reproduce the above copyright
11 *    notice, this list of conditions and the following disclaimer in
12 *    the documentation and/or other materials provided with the
13 *    distribution.
14 *
15 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
16 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
17 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
18 * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
19 * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
20 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
21 * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
22 * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
23 * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
24 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
25 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
26 * SUCH DAMAGE.
27 */
28
29#include <assert.h>
30#include <ctype.h>
31#include <errno.h>
32#include <fcntl.h>
33#include <pthread.h>
34#include <stdarg.h>
35#include <stddef.h>
36#include <stdlib.h>
37#include <string.h>
38#include <sys/mman.h>
39#include <sys/socket.h>
40#include <sys/types.h>
41#include <sys/uio.h>
42#include <sys/un.h>
43#include <time.h>
44#include <unistd.h>
45
46#include <android/set_abort_message.h>
47#include <async_safe/log.h>
48
49#include "private/CachedProperty.h"
50#include "private/ScopedPthreadMutexLocker.h"
51
52// Must be kept in sync with frameworks/base/core/java/android/util/EventLog.java.
53enum AndroidEventLogType {
54  EVENT_TYPE_INT = 0,
55  EVENT_TYPE_LONG = 1,
56  EVENT_TYPE_STRING = 2,
57  EVENT_TYPE_LIST = 3,
58  EVENT_TYPE_FLOAT = 4,
59};
60
61struct BufferOutputStream {
62 public:
63  BufferOutputStream(char* buffer, size_t size) : total(0) {
64    buffer_ = buffer;
65    end_ = buffer + size - 1;
66    pos_ = buffer_;
67    pos_[0] = '\0';
68  }
69
70  ~BufferOutputStream() {}
71
72  void Send(const char* data, int len) {
73    if (len < 0) {
74      len = strlen(data);
75    }
76
77    total += len;
78
79    while (len > 0) {
80      int avail = end_ - pos_;
81      if (avail == 0) {
82        return;
83      }
84      if (avail > len) {
85        avail = len;
86      }
87      memcpy(pos_, data, avail);
88      pos_ += avail;
89      pos_[0] = '\0';
90      len -= avail;
91    }
92  }
93
94  size_t total;
95
96 private:
97  char* buffer_;
98  char* pos_;
99  char* end_;
100};
101
102struct FdOutputStream {
103 public:
104  explicit FdOutputStream(int fd) : total(0), fd_(fd) {}
105
106  void Send(const char* data, int len) {
107    if (len < 0) {
108      len = strlen(data);
109    }
110
111    total += len;
112
113    while (len > 0) {
114      int rc = TEMP_FAILURE_RETRY(write(fd_, data, len));
115      if (rc == -1) {
116        return;
117      }
118      data += rc;
119      len -= rc;
120    }
121  }
122
123  size_t total;
124
125 private:
126  int fd_;
127};
128
129/*** formatted output implementation
130 ***/
131
132/* Parse a decimal string from 'format + *ppos',
133 * return the value, and writes the new position past
134 * the decimal string in '*ppos' on exit.
135 *
136 * NOTE: Does *not* handle a sign prefix.
137 */
138static unsigned parse_decimal(const char* format, int* ppos) {
139  const char* p = format + *ppos;
140  unsigned result = 0;
141
142  for (;;) {
143    int ch = *p;
144    unsigned d = static_cast<unsigned>(ch - '0');
145
146    if (d >= 10U) {
147      break;
148    }
149
150    result = result * 10 + d;
151    p++;
152  }
153  *ppos = p - format;
154  return result;
155}
156
157// Writes number 'value' in base 'base' into buffer 'buf' of size 'buf_size' bytes.
158// Assumes that buf_size > 0.
159static void format_unsigned(char* buf, size_t buf_size, uint64_t value, int base, bool caps) {
160  char* p = buf;
161  char* end = buf + buf_size - 1;
162
163  // Generate digit string in reverse order.
164  while (value) {
165    unsigned d = value % base;
166    value /= base;
167    if (p != end) {
168      char ch;
169      if (d < 10) {
170        ch = '0' + d;
171      } else {
172        ch = (caps ? 'A' : 'a') + (d - 10);
173      }
174      *p++ = ch;
175    }
176  }
177
178  // Special case for 0.
179  if (p == buf) {
180    if (p != end) {
181      *p++ = '0';
182    }
183  }
184  *p = '\0';
185
186  // Reverse digit string in-place.
187  size_t length = p - buf;
188  for (size_t i = 0, j = length - 1; i < j; ++i, --j) {
189    char ch = buf[i];
190    buf[i] = buf[j];
191    buf[j] = ch;
192  }
193}
194
195static void format_integer(char* buf, size_t buf_size, uint64_t value, char conversion) {
196  // Decode the conversion specifier.
197  int is_signed = (conversion == 'd' || conversion == 'i' || conversion == 'o');
198  int base = 10;
199  if (conversion == 'x' || conversion == 'X') {
200    base = 16;
201  } else if (conversion == 'o') {
202    base = 8;
203  }
204  bool caps = (conversion == 'X');
205
206  if (is_signed && static_cast<int64_t>(value) < 0) {
207    buf[0] = '-';
208    buf += 1;
209    buf_size -= 1;
210    value = static_cast<uint64_t>(-static_cast<int64_t>(value));
211  }
212  format_unsigned(buf, buf_size, value, base, caps);
213}
214
215template <typename Out>
216static void SendRepeat(Out& o, char ch, int count) {
217  char pad[8];
218  memset(pad, ch, sizeof(pad));
219
220  const int pad_size = static_cast<int>(sizeof(pad));
221  while (count > 0) {
222    int avail = count;
223    if (avail > pad_size) {
224      avail = pad_size;
225    }
226    o.Send(pad, avail);
227    count -= avail;
228  }
229}
230
231/* Perform formatted output to an output target 'o' */
232template <typename Out>
233static void out_vformat(Out& o, const char* format, va_list args) {
234  int nn = 0;
235
236  for (;;) {
237    int mm;
238    int padZero = 0;
239    int padLeft = 0;
240    char sign = '\0';
241    int width = -1;
242    int prec = -1;
243    size_t bytelen = sizeof(int);
244    int slen;
245    char buffer[32]; /* temporary buffer used to format numbers */
246
247    char c;
248
249    /* first, find all characters that are not 0 or '%' */
250    /* then send them to the output directly */
251    mm = nn;
252    do {
253      c = format[mm];
254      if (c == '\0' || c == '%') break;
255      mm++;
256    } while (1);
257
258    if (mm > nn) {
259      o.Send(format + nn, mm - nn);
260      nn = mm;
261    }
262
263    /* is this it ? then exit */
264    if (c == '\0') break;
265
266    /* nope, we are at a '%' modifier */
267    nn++;  // skip it
268
269    /* parse flags */
270    for (;;) {
271      c = format[nn++];
272      if (c == '\0') { /* single trailing '%' ? */
273        c = '%';
274        o.Send(&c, 1);
275        return;
276      } else if (c == '0') {
277        padZero = 1;
278        continue;
279      } else if (c == '-') {
280        padLeft = 1;
281        continue;
282      } else if (c == ' ' || c == '+') {
283        sign = c;
284        continue;
285      }
286      break;
287    }
288
289    /* parse field width */
290    if ((c >= '0' && c <= '9')) {
291      nn--;
292      width = static_cast<int>(parse_decimal(format, &nn));
293      c = format[nn++];
294    }
295
296    /* parse precision */
297    if (c == '.') {
298      prec = static_cast<int>(parse_decimal(format, &nn));
299      c = format[nn++];
300    }
301
302    /* length modifier */
303    switch (c) {
304      case 'h':
305        bytelen = sizeof(short);
306        if (format[nn] == 'h') {
307          bytelen = sizeof(char);
308          nn += 1;
309        }
310        c = format[nn++];
311        break;
312      case 'l':
313        bytelen = sizeof(long);
314        if (format[nn] == 'l') {
315          bytelen = sizeof(long long);
316          nn += 1;
317        }
318        c = format[nn++];
319        break;
320      case 'z':
321        bytelen = sizeof(size_t);
322        c = format[nn++];
323        break;
324      case 't':
325        bytelen = sizeof(ptrdiff_t);
326        c = format[nn++];
327        break;
328      default:;
329    }
330
331    /* conversion specifier */
332    const char* str = buffer;
333    if (c == 's') {
334      /* string */
335      str = va_arg(args, const char*);
336      if (str == NULL) {
337        str = "(null)";
338      }
339    } else if (c == 'c') {
340      /* character */
341      /* NOTE: char is promoted to int when passed through the stack */
342      buffer[0] = static_cast<char>(va_arg(args, int));
343      buffer[1] = '\0';
344    } else if (c == 'p') {
345      uint64_t value = reinterpret_cast<uintptr_t>(va_arg(args, void*));
346      buffer[0] = '0';
347      buffer[1] = 'x';
348      format_integer(buffer + 2, sizeof(buffer) - 2, value, 'x');
349    } else if (c == 'd' || c == 'i' || c == 'o' || c == 'u' || c == 'x' || c == 'X') {
350      /* integers - first read value from stack */
351      uint64_t value;
352      int is_signed = (c == 'd' || c == 'i' || c == 'o');
353
354      /* NOTE: int8_t and int16_t are promoted to int when passed
355       *       through the stack
356       */
357      switch (bytelen) {
358        case 1:
359          value = static_cast<uint8_t>(va_arg(args, int));
360          break;
361        case 2:
362          value = static_cast<uint16_t>(va_arg(args, int));
363          break;
364        case 4:
365          value = va_arg(args, uint32_t);
366          break;
367        case 8:
368          value = va_arg(args, uint64_t);
369          break;
370        default:
371          return; /* should not happen */
372      }
373
374      /* sign extension, if needed */
375      if (is_signed) {
376        int shift = 64 - 8 * bytelen;
377        value = static_cast<uint64_t>((static_cast<int64_t>(value << shift)) >> shift);
378      }
379
380      /* format the number properly into our buffer */
381      format_integer(buffer, sizeof(buffer), value, c);
382    } else if (c == '%') {
383      buffer[0] = '%';
384      buffer[1] = '\0';
385    } else {
386      __assert(__FILE__, __LINE__, "conversion specifier unsupported");
387    }
388
389    /* if we are here, 'str' points to the content that must be
390     * outputted. handle padding and alignment now */
391
392    slen = strlen(str);
393
394    if (sign != '\0' || prec != -1) {
395      __assert(__FILE__, __LINE__, "sign/precision unsupported");
396    }
397
398    if (slen < width && !padLeft) {
399      char padChar = padZero ? '0' : ' ';
400      SendRepeat(o, padChar, width - slen);
401    }
402
403    o.Send(str, slen);
404
405    if (slen < width && padLeft) {
406      char padChar = padZero ? '0' : ' ';
407      SendRepeat(o, padChar, width - slen);
408    }
409  }
410}
411
412int async_safe_format_buffer(char* buffer, size_t buffer_size, const char* format, ...) {
413  BufferOutputStream os(buffer, buffer_size);
414  va_list args;
415  va_start(args, format);
416  out_vformat(os, format, args);
417  va_end(args);
418  return os.total;
419}
420
421int async_safe_format_buffer_va_list(char* buffer, size_t buffer_size, const char* format,
422                                     va_list args) {
423  BufferOutputStream os(buffer, buffer_size);
424  out_vformat(os, format, args);
425  return os.total;
426}
427
428int async_safe_format_fd(int fd, const char* format, ...) {
429  FdOutputStream os(fd);
430  va_list args;
431  va_start(args, format);
432  out_vformat(os, format, args);
433  va_end(args);
434  return os.total;
435}
436
437static int write_stderr(const char* tag, const char* msg) {
438  iovec vec[4];
439  vec[0].iov_base = const_cast<char*>(tag);
440  vec[0].iov_len = strlen(tag);
441  vec[1].iov_base = const_cast<char*>(": ");
442  vec[1].iov_len = 2;
443  vec[2].iov_base = const_cast<char*>(msg);
444  vec[2].iov_len = strlen(msg);
445  vec[3].iov_base = const_cast<char*>("\n");
446  vec[3].iov_len = 1;
447
448  int result = TEMP_FAILURE_RETRY(writev(STDERR_FILENO, vec, 4));
449  return result;
450}
451
452static int open_log_socket() {
453  // ToDo: Ideally we want this to fail if the gid of the current
454  // process is AID_LOGD, but will have to wait until we have
455  // registered this in private/android_filesystem_config.h. We have
456  // found that all logd crashes thus far have had no problem stuffing
457  // the UNIX domain socket and moving on so not critical *today*.
458
459  int log_fd = TEMP_FAILURE_RETRY(socket(PF_UNIX, SOCK_DGRAM | SOCK_CLOEXEC | SOCK_NONBLOCK, 0));
460  if (log_fd == -1) {
461    return -1;
462  }
463
464  union {
465    struct sockaddr addr;
466    struct sockaddr_un addrUn;
467  } u;
468  memset(&u, 0, sizeof(u));
469  u.addrUn.sun_family = AF_UNIX;
470  strlcpy(u.addrUn.sun_path, "/dev/socket/logdw", sizeof(u.addrUn.sun_path));
471
472  if (TEMP_FAILURE_RETRY(connect(log_fd, &u.addr, sizeof(u.addrUn))) != 0) {
473    close(log_fd);
474    return -1;
475  }
476
477  return log_fd;
478}
479
480struct log_time {  // Wire format
481  uint32_t tv_sec;
482  uint32_t tv_nsec;
483};
484
485int async_safe_write_log(int priority, const char* tag, const char* msg) {
486  int main_log_fd = open_log_socket();
487  if (main_log_fd == -1) {
488    // Try stderr instead.
489    return write_stderr(tag, msg);
490  }
491
492  iovec vec[6];
493  char log_id = (priority == ANDROID_LOG_FATAL) ? LOG_ID_CRASH : LOG_ID_MAIN;
494  vec[0].iov_base = &log_id;
495  vec[0].iov_len = sizeof(log_id);
496  uint16_t tid = gettid();
497  vec[1].iov_base = &tid;
498  vec[1].iov_len = sizeof(tid);
499  timespec ts;
500  clock_gettime(CLOCK_REALTIME, &ts);
501  log_time realtime_ts;
502  realtime_ts.tv_sec = ts.tv_sec;
503  realtime_ts.tv_nsec = ts.tv_nsec;
504  vec[2].iov_base = &realtime_ts;
505  vec[2].iov_len = sizeof(realtime_ts);
506
507  vec[3].iov_base = &priority;
508  vec[3].iov_len = 1;
509  vec[4].iov_base = const_cast<char*>(tag);
510  vec[4].iov_len = strlen(tag) + 1;
511  vec[5].iov_base = const_cast<char*>(msg);
512  vec[5].iov_len = strlen(msg) + 1;
513
514  int result = TEMP_FAILURE_RETRY(writev(main_log_fd, vec, sizeof(vec) / sizeof(vec[0])));
515  close(main_log_fd);
516  return result;
517}
518
519int async_safe_format_log_va_list(int priority, const char* tag, const char* format, va_list args) {
520  char buffer[1024];
521  BufferOutputStream os(buffer, sizeof(buffer));
522  out_vformat(os, format, args);
523  return async_safe_write_log(priority, tag, buffer);
524}
525
526int async_safe_format_log(int priority, const char* tag, const char* format, ...) {
527  va_list args;
528  va_start(args, format);
529  int result = async_safe_format_log_va_list(priority, tag, format, args);
530  va_end(args);
531  return result;
532}
533
534void async_safe_fatal_va_list(const char* prefix, const char* format, va_list args) {
535  char msg[1024];
536  BufferOutputStream os(msg, sizeof(msg));
537
538  if (prefix) {
539    os.Send(prefix, strlen(prefix));
540    os.Send(": ", 2);
541  }
542
543  out_vformat(os, format, args);
544
545  // Log to stderr for the benefit of "adb shell" users and gtests.
546  struct iovec iov[2] = {
547      {msg, os.total}, {const_cast<char*>("\n"), 1},
548  };
549  TEMP_FAILURE_RETRY(writev(2, iov, 2));
550
551  // Log to the log for the benefit of regular app developers (whose stdout and stderr are closed).
552  async_safe_write_log(ANDROID_LOG_FATAL, "libc", msg);
553
554  android_set_abort_message(msg);
555}
556
557void async_safe_fatal_no_abort(const char* fmt, ...) {
558  va_list args;
559  va_start(args, fmt);
560  async_safe_fatal_va_list(nullptr, fmt, args);
561  va_end(args);
562}
563