blob: 2380e686d91f30c168b550610eff9dd963482ac0 [file] [log] [blame]
Christopher Ferris7a3681e2017-04-24 17:48:32 -07001/*
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>
Josh Gaod3711332020-08-20 16:27:01 -070033#include <linux/net.h>
Christopher Ferris7a3681e2017-04-24 17:48:32 -070034#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>
Josh Gaof6e5b582018-06-01 15:30:54 -070041#include <sys/syscall.h>
Christopher Ferris7a3681e2017-04-24 17:48:32 -070042#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"
Elliott Hughes8aecba72017-10-17 15:34:41 -070052#include "private/ErrnoRestorer.h"
Christopher Ferris7a3681e2017-04-24 17:48:32 -070053#include "private/ScopedPthreadMutexLocker.h"
54
Josh Gaod3711332020-08-20 16:27:01 -070055// Don't call libc's close or socket, since it might call back into us as a result of fdsan/fdtrack.
Josh Gaof6e5b582018-06-01 15:30:54 -070056#pragma GCC poison close
57static int __close(int fd) {
58 return syscall(__NR_close, fd);
59}
60
Josh Gaod3711332020-08-20 16:27:01 -070061static 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
Christopher Ferris7a3681e2017-04-24 17:48:32 -070071// Must be kept in sync with frameworks/base/core/java/android/util/EventLog.java.
72enum 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
80struct BufferOutputStream {
81 public:
Christopher Ferris92476402017-08-22 11:24:09 -070082 BufferOutputStream(char* buffer, size_t size) : total(0), pos_(buffer), avail_(size) {
83 if (avail_ > 0) pos_[0] = '\0';
Christopher Ferris7a3681e2017-04-24 17:48:32 -070084 }
Christopher Ferris92476402017-08-22 11:24:09 -070085 ~BufferOutputStream() = default;
Christopher Ferris7a3681e2017-04-24 17:48:32 -070086
87 void Send(const char* data, int len) {
88 if (len < 0) {
89 len = strlen(data);
90 }
Christopher Ferris7a3681e2017-04-24 17:48:32 -070091 total += len;
92
Christopher Ferris92476402017-08-22 11:24:09 -070093 if (avail_ <= 1) {
94 // No space to put anything else.
95 return;
Christopher Ferris7a3681e2017-04-24 17:48:32 -070096 }
Christopher Ferris92476402017-08-22 11:24:09 -070097
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;
Christopher Ferris7a3681e2017-04-24 17:48:32 -0700105 }
106
107 size_t total;
108
109 private:
Christopher Ferris7a3681e2017-04-24 17:48:32 -0700110 char* pos_;
Christopher Ferris92476402017-08-22 11:24:09 -0700111 size_t avail_;
Christopher Ferris7a3681e2017-04-24 17:48:32 -0700112};
113
114struct FdOutputStream {
115 public:
116 explicit FdOutputStream(int fd) : total(0), fd_(fd) {}
117
118 void Send(const char* data, int len) {
119 if (len < 0) {
120 len = strlen(data);
121 }
Christopher Ferris7a3681e2017-04-24 17:48:32 -0700122 total += len;
123
124 while (len > 0) {
Christopher Ferris92476402017-08-22 11:24:09 -0700125 ssize_t bytes = TEMP_FAILURE_RETRY(write(fd_, data, len));
126 if (bytes == -1) {
Christopher Ferris7a3681e2017-04-24 17:48:32 -0700127 return;
128 }
Christopher Ferris92476402017-08-22 11:24:09 -0700129 data += bytes;
130 len -= bytes;
Christopher Ferris7a3681e2017-04-24 17:48:32 -0700131 }
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 */
149static 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.
170static 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
206static 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
226template <typename Out>
227static 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' */
243template <typename Out>
244static 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;
zijunzhao75c36fe2022-01-28 19:22:24 +0000254 bool alternate = false;
Christopher Ferris7a3681e2017-04-24 17:48:32 -0700255 size_t bytelen = sizeof(int);
256 int slen;
257 char buffer[32]; /* temporary buffer used to format numbers */
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;
zijunzhao75c36fe2022-01-28 19:22:24 +0000297 } else if (c == '#') {
298 alternate = true;
299 continue;
Christopher Ferris7a3681e2017-04-24 17:48:32 -0700300 }
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*);
Christopher Ferris7a3681e2017-04-24 17:48:32 -0700351 } 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');
zijunzhao75c36fe2022-01-28 19:22:24 +0000361 } else if (c == 'm') {
362 char buf[256];
363 str = strerror_r(errno, buf, sizeof(buf));
Christopher Ferris7a3681e2017-04-24 17:48:32 -0700364 } else if (c == 'd' || c == 'i' || c == 'o' || c == 'u' || c == 'x' || c == 'X') {
365 /* integers - first read value from stack */
366 uint64_t value;
367 int is_signed = (c == 'd' || c == 'i' || c == 'o');
368
369 /* NOTE: int8_t and int16_t are promoted to int when passed
370 * through the stack
371 */
372 switch (bytelen) {
373 case 1:
374 value = static_cast<uint8_t>(va_arg(args, int));
375 break;
376 case 2:
377 value = static_cast<uint16_t>(va_arg(args, int));
378 break;
379 case 4:
380 value = va_arg(args, uint32_t);
381 break;
382 case 8:
383 value = va_arg(args, uint64_t);
384 break;
385 default:
386 return; /* should not happen */
387 }
388
389 /* sign extension, if needed */
390 if (is_signed) {
391 int shift = 64 - 8 * bytelen;
392 value = static_cast<uint64_t>((static_cast<int64_t>(value << shift)) >> shift);
393 }
394
zijunzhao75c36fe2022-01-28 19:22:24 +0000395 if (alternate && value != 0 && (c == 'x' || c == 'o')) {
396 if (c == 'x') {
397 buffer[0] = '0';
398 buffer[1] = 'x';
399 format_integer(buffer + 2, sizeof(buffer) - 2, value, c);
400 } else {
401 buffer[0] = '0';
402 format_integer(buffer + 1, sizeof(buffer) - 1, value, c);
403 }
404 } else {
405 /* format the number properly into our buffer */
406 format_integer(buffer, sizeof(buffer), value, c);
407 }
Christopher Ferris7a3681e2017-04-24 17:48:32 -0700408 } else if (c == '%') {
409 buffer[0] = '%';
410 buffer[1] = '\0';
411 } else {
412 __assert(__FILE__, __LINE__, "conversion specifier unsupported");
413 }
414
zijunzhao75c36fe2022-01-28 19:22:24 +0000415 if (str == nullptr) {
416 str = "(null)";
417 }
418
Christopher Ferris7a3681e2017-04-24 17:48:32 -0700419 /* if we are here, 'str' points to the content that must be
420 * outputted. handle padding and alignment now */
421
422 slen = strlen(str);
423
424 if (sign != '\0' || prec != -1) {
425 __assert(__FILE__, __LINE__, "sign/precision unsupported");
426 }
427
428 if (slen < width && !padLeft) {
429 char padChar = padZero ? '0' : ' ';
430 SendRepeat(o, padChar, width - slen);
431 }
432
433 o.Send(str, slen);
434
435 if (slen < width && padLeft) {
436 char padChar = padZero ? '0' : ' ';
437 SendRepeat(o, padChar, width - slen);
438 }
439 }
440}
441
Christopher Ferris7a3681e2017-04-24 17:48:32 -0700442int async_safe_format_buffer_va_list(char* buffer, size_t buffer_size, const char* format,
443 va_list args) {
444 BufferOutputStream os(buffer, buffer_size);
445 out_vformat(os, format, args);
446 return os.total;
447}
448
Christopher Ferris92476402017-08-22 11:24:09 -0700449int async_safe_format_buffer(char* buffer, size_t buffer_size, const char* format, ...) {
450 va_list args;
451 va_start(args, format);
452 int buffer_len = async_safe_format_buffer_va_list(buffer, buffer_size, format, args);
453 va_end(args);
454 return buffer_len;
455}
456
Ryan Prichard5de9a31c2018-10-02 18:13:28 -0700457int async_safe_format_fd_va_list(int fd, const char* format, va_list args) {
Christopher Ferris7a3681e2017-04-24 17:48:32 -0700458 FdOutputStream os(fd);
Ryan Prichard5de9a31c2018-10-02 18:13:28 -0700459 out_vformat(os, format, args);
460 return os.total;
461}
462
463int async_safe_format_fd(int fd, const char* format, ...) {
Christopher Ferris7a3681e2017-04-24 17:48:32 -0700464 va_list args;
465 va_start(args, format);
Ryan Prichard5de9a31c2018-10-02 18:13:28 -0700466 int result = async_safe_format_fd_va_list(fd, format, args);
Christopher Ferris7a3681e2017-04-24 17:48:32 -0700467 va_end(args);
Ryan Prichard5de9a31c2018-10-02 18:13:28 -0700468 return result;
Christopher Ferris7a3681e2017-04-24 17:48:32 -0700469}
470
471static int write_stderr(const char* tag, const char* msg) {
472 iovec vec[4];
473 vec[0].iov_base = const_cast<char*>(tag);
474 vec[0].iov_len = strlen(tag);
475 vec[1].iov_base = const_cast<char*>(": ");
476 vec[1].iov_len = 2;
477 vec[2].iov_base = const_cast<char*>(msg);
478 vec[2].iov_len = strlen(msg);
479 vec[3].iov_base = const_cast<char*>("\n");
480 vec[3].iov_len = 1;
481
482 int result = TEMP_FAILURE_RETRY(writev(STDERR_FILENO, vec, 4));
483 return result;
484}
485
486static int open_log_socket() {
487 // ToDo: Ideally we want this to fail if the gid of the current
488 // process is AID_LOGD, but will have to wait until we have
489 // registered this in private/android_filesystem_config.h. We have
490 // found that all logd crashes thus far have had no problem stuffing
491 // the UNIX domain socket and moving on so not critical *today*.
492
Josh Gaod3711332020-08-20 16:27:01 -0700493 int log_fd = TEMP_FAILURE_RETRY(__socket(PF_UNIX, SOCK_DGRAM | SOCK_CLOEXEC | SOCK_NONBLOCK, 0));
Christopher Ferris7a3681e2017-04-24 17:48:32 -0700494 if (log_fd == -1) {
495 return -1;
496 }
497
498 union {
499 struct sockaddr addr;
500 struct sockaddr_un addrUn;
501 } u;
502 memset(&u, 0, sizeof(u));
503 u.addrUn.sun_family = AF_UNIX;
504 strlcpy(u.addrUn.sun_path, "/dev/socket/logdw", sizeof(u.addrUn.sun_path));
505
506 if (TEMP_FAILURE_RETRY(connect(log_fd, &u.addr, sizeof(u.addrUn))) != 0) {
Josh Gaof6e5b582018-06-01 15:30:54 -0700507 __close(log_fd);
Christopher Ferris7a3681e2017-04-24 17:48:32 -0700508 return -1;
509 }
510
511 return log_fd;
512}
513
Christopher Ferris7a3681e2017-04-24 17:48:32 -0700514struct log_time { // Wire format
515 uint32_t tv_sec;
516 uint32_t tv_nsec;
517};
518
519int async_safe_write_log(int priority, const char* tag, const char* msg) {
520 int main_log_fd = open_log_socket();
521 if (main_log_fd == -1) {
522 // Try stderr instead.
523 return write_stderr(tag, msg);
524 }
525
526 iovec vec[6];
527 char log_id = (priority == ANDROID_LOG_FATAL) ? LOG_ID_CRASH : LOG_ID_MAIN;
528 vec[0].iov_base = &log_id;
529 vec[0].iov_len = sizeof(log_id);
530 uint16_t tid = gettid();
531 vec[1].iov_base = &tid;
532 vec[1].iov_len = sizeof(tid);
533 timespec ts;
Elliott Hughes53dc9dd2017-09-19 14:02:50 -0700534 clock_gettime(CLOCK_REALTIME, &ts);
Christopher Ferris7a3681e2017-04-24 17:48:32 -0700535 log_time realtime_ts;
536 realtime_ts.tv_sec = ts.tv_sec;
537 realtime_ts.tv_nsec = ts.tv_nsec;
538 vec[2].iov_base = &realtime_ts;
539 vec[2].iov_len = sizeof(realtime_ts);
540
541 vec[3].iov_base = &priority;
542 vec[3].iov_len = 1;
543 vec[4].iov_base = const_cast<char*>(tag);
544 vec[4].iov_len = strlen(tag) + 1;
545 vec[5].iov_base = const_cast<char*>(msg);
546 vec[5].iov_len = strlen(msg) + 1;
547
548 int result = TEMP_FAILURE_RETRY(writev(main_log_fd, vec, sizeof(vec) / sizeof(vec[0])));
Josh Gaof6e5b582018-06-01 15:30:54 -0700549 __close(main_log_fd);
Christopher Ferris7a3681e2017-04-24 17:48:32 -0700550 return result;
551}
552
553int async_safe_format_log_va_list(int priority, const char* tag, const char* format, va_list args) {
Elliott Hughes8aecba72017-10-17 15:34:41 -0700554 ErrnoRestorer errno_restorer;
Christopher Ferris7a3681e2017-04-24 17:48:32 -0700555 char buffer[1024];
556 BufferOutputStream os(buffer, sizeof(buffer));
557 out_vformat(os, format, args);
558 return async_safe_write_log(priority, tag, buffer);
559}
560
561int async_safe_format_log(int priority, const char* tag, const char* format, ...) {
562 va_list args;
563 va_start(args, format);
564 int result = async_safe_format_log_va_list(priority, tag, format, args);
565 va_end(args);
566 return result;
567}
568
569void async_safe_fatal_va_list(const char* prefix, const char* format, va_list args) {
570 char msg[1024];
571 BufferOutputStream os(msg, sizeof(msg));
572
573 if (prefix) {
574 os.Send(prefix, strlen(prefix));
575 os.Send(": ", 2);
576 }
577
578 out_vformat(os, format, args);
579
580 // Log to stderr for the benefit of "adb shell" users and gtests.
581 struct iovec iov[2] = {
Ryan Prichard5258c252018-05-01 17:59:59 -0700582 {msg, strlen(msg)}, {const_cast<char*>("\n"), 1},
Christopher Ferris7a3681e2017-04-24 17:48:32 -0700583 };
584 TEMP_FAILURE_RETRY(writev(2, iov, 2));
585
586 // Log to the log for the benefit of regular app developers (whose stdout and stderr are closed).
587 async_safe_write_log(ANDROID_LOG_FATAL, "libc", msg);
588
589 android_set_abort_message(msg);
590}
591
Elliott Hughes695713e2017-06-20 17:28:42 -0700592void async_safe_fatal_no_abort(const char* fmt, ...) {
Christopher Ferris7a3681e2017-04-24 17:48:32 -0700593 va_list args;
594 va_start(args, fmt);
595 async_safe_fatal_va_list(nullptr, fmt, args);
596 va_end(args);
Christopher Ferris7a3681e2017-04-24 17:48:32 -0700597}