Elliott Hughes | eb4f614 | 2011-07-15 17:43:51 -0700 | [diff] [blame^] | 1 | // Copyright 2011 Google Inc. All Rights Reserved. |
| 2 | // Author: enh@google.com (Elliott Hughes) |
| 3 | |
| 4 | #include "logging.h" |
| 5 | |
| 6 | #include "scoped_ptr.h" |
| 7 | #include "stringprintf.h" |
| 8 | |
| 9 | #include <cstdio> |
| 10 | #include <cstring> |
| 11 | #include <execinfo.h> |
| 12 | #include <iostream> |
| 13 | #include <sys/types.h> |
| 14 | #include <unistd.h> |
| 15 | |
| 16 | // glibc doesn't expose gettid(2). |
| 17 | #define __KERNEL__ |
| 18 | # include <linux/unistd.h> |
| 19 | #ifdef _syscall0 |
| 20 | _syscall0(pid_t,gettid) |
| 21 | #else |
| 22 | pid_t gettid() { return syscall(__NR_gettid);} |
| 23 | #endif |
| 24 | #undef __KERNEL__ |
| 25 | |
| 26 | static void dumpStackTrace(std::ostream& os) { |
| 27 | // Get the raw stack frames. |
| 28 | size_t MAX_STACK_FRAMES = 64; |
| 29 | void* stack_frames[MAX_STACK_FRAMES]; |
| 30 | size_t frame_count = backtrace(stack_frames, MAX_STACK_FRAMES); |
| 31 | |
| 32 | // Turn them into something human-readable with symbols. |
| 33 | // TODO: in practice, we may find that we should use backtrace_symbols_fd |
| 34 | // to avoid allocation, rather than use our own custom formatting. |
| 35 | art::scoped_ptr_malloc<char*> strings(backtrace_symbols(stack_frames, frame_count)); |
| 36 | if (strings.get() == NULL) { |
| 37 | os << "backtrace_symbols failed: " << strerror(errno) << std::endl; |
| 38 | return; |
| 39 | } |
| 40 | |
| 41 | for (size_t i = 0; i < frame_count; ++i) { |
| 42 | os << StringPrintf("\t#%02d %s", i, strings.get()[i]) << std::endl; |
| 43 | } |
| 44 | } |
| 45 | |
| 46 | LogMessage::LogMessage(const char* file, int line, LogSeverity severity, int error) |
| 47 | : severity_(severity), errno_(error) |
| 48 | { |
| 49 | const char* last_slash = strrchr(file, '/'); |
| 50 | const char* leaf = (last_slash == NULL) ? file : last_slash + 1; |
| 51 | stream() << StringPrintf("%c %5d %5d %s:%d] ", |
| 52 | "IWEF"[severity], getpid(), gettid(), leaf, line); |
| 53 | } |
| 54 | |
| 55 | LogMessage::~LogMessage() { |
| 56 | if (errno_ != -1) { |
| 57 | stream() << ": " << strerror(errno); |
| 58 | } |
| 59 | stream() << std::endl; |
| 60 | if (severity_ == FATAL) { |
| 61 | stream() << "Aborting:" << std::endl; |
| 62 | dumpStackTrace(stream()); |
| 63 | abort(); |
| 64 | } |
| 65 | } |
| 66 | |
| 67 | std::ostream& LogMessage::stream() { |
| 68 | return std::cerr; |
| 69 | } |