blob: 420560f7b04dc9645bfd04a95ec7df316b758a8c [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;
Christopher Ferris35759fa2023-03-20 16:31:18 -0700257 char buffer[64]; // temporary buffer used to format numbers/format errno string
Christopher Ferris7a3681e2017-04-24 17:48:32 -0700258
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') {
Christopher Ferris35759fa2023-03-20 16:31:18 -0700362 strerror_r(errno, buffer, sizeof(buffer));
Christopher Ferris7a3681e2017-04-24 17:48:32 -0700363 } else if (c == 'd' || c == 'i' || c == 'o' || c == 'u' || c == 'x' || c == 'X') {
364 /* integers - first read value from stack */
365 uint64_t value;
366 int is_signed = (c == 'd' || c == 'i' || c == 'o');
367
368 /* NOTE: int8_t and int16_t are promoted to int when passed
369 * through the stack
370 */
371 switch (bytelen) {
372 case 1:
373 value = static_cast<uint8_t>(va_arg(args, int));
374 break;
375 case 2:
376 value = static_cast<uint16_t>(va_arg(args, int));
377 break;
378 case 4:
379 value = va_arg(args, uint32_t);
380 break;
381 case 8:
382 value = va_arg(args, uint64_t);
383 break;
384 default:
385 return; /* should not happen */
386 }
387
388 /* sign extension, if needed */
389 if (is_signed) {
390 int shift = 64 - 8 * bytelen;
391 value = static_cast<uint64_t>((static_cast<int64_t>(value << shift)) >> shift);
392 }
393
zijunzhao75c36fe2022-01-28 19:22:24 +0000394 if (alternate && value != 0 && (c == 'x' || c == 'o')) {
395 if (c == 'x') {
396 buffer[0] = '0';
397 buffer[1] = 'x';
398 format_integer(buffer + 2, sizeof(buffer) - 2, value, c);
399 } else {
400 buffer[0] = '0';
401 format_integer(buffer + 1, sizeof(buffer) - 1, value, c);
402 }
403 } else {
404 /* format the number properly into our buffer */
405 format_integer(buffer, sizeof(buffer), value, c);
406 }
Christopher Ferris7a3681e2017-04-24 17:48:32 -0700407 } else if (c == '%') {
408 buffer[0] = '%';
409 buffer[1] = '\0';
410 } else {
411 __assert(__FILE__, __LINE__, "conversion specifier unsupported");
412 }
413
zijunzhao75c36fe2022-01-28 19:22:24 +0000414 if (str == nullptr) {
415 str = "(null)";
416 }
417
Christopher Ferris7a3681e2017-04-24 17:48:32 -0700418 /* if we are here, 'str' points to the content that must be
419 * outputted. handle padding and alignment now */
420
421 slen = strlen(str);
422
423 if (sign != '\0' || prec != -1) {
424 __assert(__FILE__, __LINE__, "sign/precision unsupported");
425 }
426
427 if (slen < width && !padLeft) {
428 char padChar = padZero ? '0' : ' ';
429 SendRepeat(o, padChar, width - slen);
430 }
431
432 o.Send(str, slen);
433
434 if (slen < width && padLeft) {
435 char padChar = padZero ? '0' : ' ';
436 SendRepeat(o, padChar, width - slen);
437 }
438 }
439}
440
Christopher Ferris7a3681e2017-04-24 17:48:32 -0700441int async_safe_format_buffer_va_list(char* buffer, size_t buffer_size, const char* format,
442 va_list args) {
443 BufferOutputStream os(buffer, buffer_size);
444 out_vformat(os, format, args);
445 return os.total;
446}
447
Christopher Ferris92476402017-08-22 11:24:09 -0700448int async_safe_format_buffer(char* buffer, size_t buffer_size, const char* format, ...) {
449 va_list args;
450 va_start(args, format);
451 int buffer_len = async_safe_format_buffer_va_list(buffer, buffer_size, format, args);
452 va_end(args);
453 return buffer_len;
454}
455
Ryan Prichard5de9a31c2018-10-02 18:13:28 -0700456int async_safe_format_fd_va_list(int fd, const char* format, va_list args) {
Christopher Ferris7a3681e2017-04-24 17:48:32 -0700457 FdOutputStream os(fd);
Ryan Prichard5de9a31c2018-10-02 18:13:28 -0700458 out_vformat(os, format, args);
459 return os.total;
460}
461
462int async_safe_format_fd(int fd, const char* format, ...) {
Christopher Ferris7a3681e2017-04-24 17:48:32 -0700463 va_list args;
464 va_start(args, format);
Ryan Prichard5de9a31c2018-10-02 18:13:28 -0700465 int result = async_safe_format_fd_va_list(fd, format, args);
Christopher Ferris7a3681e2017-04-24 17:48:32 -0700466 va_end(args);
Ryan Prichard5de9a31c2018-10-02 18:13:28 -0700467 return result;
Christopher Ferris7a3681e2017-04-24 17:48:32 -0700468}
469
470static int write_stderr(const char* tag, const char* msg) {
471 iovec vec[4];
472 vec[0].iov_base = const_cast<char*>(tag);
473 vec[0].iov_len = strlen(tag);
474 vec[1].iov_base = const_cast<char*>(": ");
475 vec[1].iov_len = 2;
476 vec[2].iov_base = const_cast<char*>(msg);
477 vec[2].iov_len = strlen(msg);
478 vec[3].iov_base = const_cast<char*>("\n");
479 vec[3].iov_len = 1;
480
481 int result = TEMP_FAILURE_RETRY(writev(STDERR_FILENO, vec, 4));
482 return result;
483}
484
485static int open_log_socket() {
486 // ToDo: Ideally we want this to fail if the gid of the current
487 // process is AID_LOGD, but will have to wait until we have
488 // registered this in private/android_filesystem_config.h. We have
489 // found that all logd crashes thus far have had no problem stuffing
490 // the UNIX domain socket and moving on so not critical *today*.
491
Josh Gaod3711332020-08-20 16:27:01 -0700492 int log_fd = TEMP_FAILURE_RETRY(__socket(PF_UNIX, SOCK_DGRAM | SOCK_CLOEXEC | SOCK_NONBLOCK, 0));
Christopher Ferris7a3681e2017-04-24 17:48:32 -0700493 if (log_fd == -1) {
494 return -1;
495 }
496
497 union {
498 struct sockaddr addr;
499 struct sockaddr_un addrUn;
500 } u;
501 memset(&u, 0, sizeof(u));
502 u.addrUn.sun_family = AF_UNIX;
503 strlcpy(u.addrUn.sun_path, "/dev/socket/logdw", sizeof(u.addrUn.sun_path));
504
505 if (TEMP_FAILURE_RETRY(connect(log_fd, &u.addr, sizeof(u.addrUn))) != 0) {
Josh Gaof6e5b582018-06-01 15:30:54 -0700506 __close(log_fd);
Christopher Ferris7a3681e2017-04-24 17:48:32 -0700507 return -1;
508 }
509
510 return log_fd;
511}
512
Christopher Ferris7a3681e2017-04-24 17:48:32 -0700513struct log_time { // Wire format
514 uint32_t tv_sec;
515 uint32_t tv_nsec;
516};
517
518int async_safe_write_log(int priority, const char* tag, const char* msg) {
519 int main_log_fd = open_log_socket();
520 if (main_log_fd == -1) {
521 // Try stderr instead.
522 return write_stderr(tag, msg);
523 }
524
525 iovec vec[6];
526 char log_id = (priority == ANDROID_LOG_FATAL) ? LOG_ID_CRASH : LOG_ID_MAIN;
527 vec[0].iov_base = &log_id;
528 vec[0].iov_len = sizeof(log_id);
529 uint16_t tid = gettid();
530 vec[1].iov_base = &tid;
531 vec[1].iov_len = sizeof(tid);
532 timespec ts;
Elliott Hughes53dc9dd2017-09-19 14:02:50 -0700533 clock_gettime(CLOCK_REALTIME, &ts);
Christopher Ferris7a3681e2017-04-24 17:48:32 -0700534 log_time realtime_ts;
535 realtime_ts.tv_sec = ts.tv_sec;
536 realtime_ts.tv_nsec = ts.tv_nsec;
537 vec[2].iov_base = &realtime_ts;
538 vec[2].iov_len = sizeof(realtime_ts);
539
540 vec[3].iov_base = &priority;
541 vec[3].iov_len = 1;
542 vec[4].iov_base = const_cast<char*>(tag);
543 vec[4].iov_len = strlen(tag) + 1;
544 vec[5].iov_base = const_cast<char*>(msg);
545 vec[5].iov_len = strlen(msg) + 1;
546
547 int result = TEMP_FAILURE_RETRY(writev(main_log_fd, vec, sizeof(vec) / sizeof(vec[0])));
Josh Gaof6e5b582018-06-01 15:30:54 -0700548 __close(main_log_fd);
Christopher Ferris7a3681e2017-04-24 17:48:32 -0700549 return result;
550}
551
552int async_safe_format_log_va_list(int priority, const char* tag, const char* format, va_list args) {
Elliott Hughes8aecba72017-10-17 15:34:41 -0700553 ErrnoRestorer errno_restorer;
Christopher Ferris7a3681e2017-04-24 17:48:32 -0700554 char buffer[1024];
555 BufferOutputStream os(buffer, sizeof(buffer));
556 out_vformat(os, format, args);
557 return async_safe_write_log(priority, tag, buffer);
558}
559
560int async_safe_format_log(int priority, const char* tag, const char* format, ...) {
561 va_list args;
562 va_start(args, format);
563 int result = async_safe_format_log_va_list(priority, tag, format, args);
564 va_end(args);
565 return result;
566}
567
568void async_safe_fatal_va_list(const char* prefix, const char* format, va_list args) {
569 char msg[1024];
570 BufferOutputStream os(msg, sizeof(msg));
571
572 if (prefix) {
573 os.Send(prefix, strlen(prefix));
574 os.Send(": ", 2);
575 }
576
577 out_vformat(os, format, args);
578
579 // Log to stderr for the benefit of "adb shell" users and gtests.
580 struct iovec iov[2] = {
Ryan Prichard5258c252018-05-01 17:59:59 -0700581 {msg, strlen(msg)}, {const_cast<char*>("\n"), 1},
Christopher Ferris7a3681e2017-04-24 17:48:32 -0700582 };
583 TEMP_FAILURE_RETRY(writev(2, iov, 2));
584
585 // Log to the log for the benefit of regular app developers (whose stdout and stderr are closed).
586 async_safe_write_log(ANDROID_LOG_FATAL, "libc", msg);
587
588 android_set_abort_message(msg);
589}
590
Elliott Hughes695713e2017-06-20 17:28:42 -0700591void async_safe_fatal_no_abort(const char* fmt, ...) {
Christopher Ferris7a3681e2017-04-24 17:48:32 -0700592 va_list args;
593 va_start(args, fmt);
594 async_safe_fatal_va_list(nullptr, fmt, args);
595 va_end(args);
Christopher Ferris7a3681e2017-04-24 17:48:32 -0700596}