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