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