1 // Copyright 2008 Google Inc. All Rights Reserved.
2 // Author: Satoru Takabayashi
4 // Implementation of InstallFailureSignalHandler().
7 #include "stacktrace.h"
9 #include "glog/logging.h"
13 #ifdef HAVE_UCONTEXT_H
14 # include <ucontext.h>
18 _START_GOOGLE_NAMESPACE_
22 // We'll install the failure signal handler for these signals. We could
23 // use strsignal() to get signal names, but we don't use it to avoid
24 // introducing yet another #ifdef complication.
26 // The list should be synced with the comment in signalhandler.h.
30 } kFailureSignals[] = {
31 { SIGSEGV, "SIGSEGV" },
34 { SIGABRT, "SIGABRT" },
36 { SIGTERM, "SIGTERM" },
39 // Returns the program counter from signal context, NULL if unknown.
40 void* GetPC(void* ucontext_in_void) {
41 #if defined(HAVE_UCONTEXT_H) && defined(PC_FROM_UCONTEXT)
42 if (ucontext_in_void != NULL) {
43 ucontext_t *context = reinterpret_cast<ucontext_t *>(ucontext_in_void);
44 return (void*)context->PC_FROM_UCONTEXT;
50 // The class is used for formatting error messages. We don't use printf()
51 // as it's not async signal safe.
52 class MinimalFormatter {
54 MinimalFormatter(char *buffer, int size)
60 // Returns the number of bytes written in the buffer.
61 int num_bytes_written() const { return cursor_ - buffer_; }
63 // Appends string from "str" and updates the internal cursor.
64 void AppendString(const char* str) {
66 while (str[i] != '\0' && cursor_ + i < end_) {
73 // Formats "number" in "radix" and updates the internal cursor.
74 // Lowercase letters are used for 'a' - 'z'.
75 void AppendUint64(uint64 number, int radix) {
77 while (cursor_ + i < end_) {
78 const int tmp = number % radix;
80 cursor_[i] = (tmp < 10 ? '0' + tmp : 'a' + tmp - 10);
86 // Reverse the bytes written.
87 std::reverse(cursor_, cursor_ + i);
91 // Formats "number" as hexadecimal number, and updates the internal
92 // cursor. Padding will be added in front if needed.
93 void AppendHexWithPadding(uint64 number, int width) {
94 char* start = cursor_;
96 AppendUint64(number, 16);
97 // Move to right and add padding in front if needed.
98 if (cursor_ < start + width) {
99 const int64 delta = start + width - cursor_;
100 std::copy(start, cursor_, start + delta);
101 std::fill(start, start + delta, ' ');
102 cursor_ = start + width;
109 const char * const end_;
112 // Writes the given data with the size to the standard error.
113 void WriteToStderr(const char* data, int size) {
114 write(STDERR_FILENO, data, size);
117 // The writer function can be changed by InstallFailureWriter().
118 void (*g_failure_writer)(const char* data, int size) = WriteToStderr;
120 // Dumps time information. We don't dump human-readable time information
121 // as localtime() is not guaranteed to be async signal safe.
122 void DumpTimeInfo() {
123 time_t time_in_sec = time(NULL);
124 char buf[256]; // Big enough for time info.
125 MinimalFormatter formatter(buf, sizeof(buf));
126 formatter.AppendString("*** Aborted at ");
127 formatter.AppendUint64(time_in_sec, 10);
128 formatter.AppendString(" (unix time)");
129 formatter.AppendString(" try \"date -d @");
130 formatter.AppendUint64(time_in_sec, 10);
131 formatter.AppendString("\" if you are using GNU date ***\n");
132 g_failure_writer(buf, formatter.num_bytes_written());
135 // Dumps information about the signal to STDERR.
136 void DumpSignalInfo(int signal_number, siginfo_t *siginfo) {
137 // Get the signal name.
138 const char* signal_name = NULL;
139 for (int i = 0; i < ARRAYSIZE(kFailureSignals); ++i) {
140 if (signal_number == kFailureSignals[i].number) {
141 signal_name = kFailureSignals[i].name;
145 char buf[256]; // Big enough for signal info.
146 MinimalFormatter formatter(buf, sizeof(buf));
148 formatter.AppendString("*** ");
150 formatter.AppendString(signal_name);
152 // Use the signal number if the name is unknown. The signal name
153 // should be known, but just in case.
154 formatter.AppendString("Signal ");
155 formatter.AppendUint64(signal_number, 10);
157 formatter.AppendString(" (@0x");
158 formatter.AppendUint64(reinterpret_cast<uintptr_t>(siginfo->si_addr), 16);
159 formatter.AppendString(")");
160 formatter.AppendString(" received by PID ");
161 formatter.AppendUint64(getpid(), 10);
162 formatter.AppendString(" (TID 0x");
163 // We assume pthread_t is an integral number or a pointer, rather
164 // than a complex struct. In some environments, pthread_self()
165 // returns an uint64 but in some other environments pthread_self()
166 // returns a pointer. Hence we use C-style cast here, rather than
167 // reinterpret/static_cast, to support both types of environments.
168 formatter.AppendUint64((uintptr_t)pthread_self(), 16);
169 formatter.AppendString(") ");
170 // Only linux has the PID of the signal sender in si_pid.
172 formatter.AppendString("from PID ");
173 formatter.AppendUint64(siginfo->si_pid, 10);
174 formatter.AppendString("; ");
176 formatter.AppendString("stack trace: ***\n");
177 g_failure_writer(buf, formatter.num_bytes_written());
180 // Dumps information about the stack frame to STDERR.
181 void DumpStackFrameInfo(const char* prefix, void* pc) {
182 // Get the symbol name.
183 const char *symbol = "(unknown)";
184 char symbolized[1024]; // Big enough for a sane symbol.
185 // Symbolizes the previous address of pc because pc may be in the
187 if (Symbolize(reinterpret_cast<char *>(pc) - 1,
188 symbolized, sizeof(symbolized))) {
192 char buf[1024]; // Big enough for stack frame info.
193 MinimalFormatter formatter(buf, sizeof(buf));
195 formatter.AppendString(prefix);
196 formatter.AppendString("@ ");
197 const int width = 2 * sizeof(void*) + 2; // + 2 for "0x".
198 formatter.AppendHexWithPadding(reinterpret_cast<uintptr_t>(pc), width);
199 formatter.AppendString(" ");
200 formatter.AppendString(symbol);
201 formatter.AppendString("\n");
202 g_failure_writer(buf, formatter.num_bytes_written());
205 // Invoke the default signal handler.
206 void InvokeDefaultSignalHandler(int signal_number) {
207 struct sigaction sig_action = {}; // Zero-clear.
208 sigemptyset(&sig_action.sa_mask);
209 sig_action.sa_handler = SIG_DFL;
210 sigaction(signal_number, &sig_action, NULL);
211 kill(getpid(), signal_number);
214 // This variable is used for protecting FailureSignalHandler() from
215 // dumping stuff while another thread is doing it. Our policy is to let
216 // the first thread dump stuff and let other threads wait.
217 // See also comments in FailureSignalHandler().
218 static pthread_t* g_entered_thread_id_pointer = NULL;
220 // Dumps signal and stack frame information, and invokes the default
221 // signal handler once our job is done.
222 void FailureSignalHandler(int signal_number,
223 siginfo_t *signal_info,
225 // First check if we've already entered the function. We use an atomic
226 // compare and swap operation for platforms that support it. For other
227 // platforms, we use a naive method that could lead to a subtle race.
229 // We assume pthread_self() is async signal safe, though it's not
230 // officially guaranteed.
231 pthread_t my_thread_id = pthread_self();
232 // NOTE: We could simply use pthread_t rather than pthread_t* for this,
233 // if pthread_self() is guaranteed to return non-zero value for thread
234 // ids, but there is no such guarantee. We need to distinguish if the
235 // old value (value returned from __sync_val_compare_and_swap) is
236 // different from the original value (in this case NULL).
237 pthread_t* old_thread_id_pointer =
238 glog_internal_namespace_::sync_val_compare_and_swap(
239 &g_entered_thread_id_pointer,
240 static_cast<pthread_t*>(NULL),
242 if (old_thread_id_pointer != NULL) {
243 // We've already entered the signal handler. What should we do?
244 if (pthread_equal(my_thread_id, *g_entered_thread_id_pointer)) {
245 // It looks the current thread is reentering the signal handler.
246 // Something must be going wrong (maybe we are reentering by another
247 // type of signal?). Kill ourself by the default signal handler.
248 InvokeDefaultSignalHandler(signal_number);
250 // Another thread is dumping stuff. Let's wait until that thread
251 // finishes the job and kills the process.
256 // This is the first time we enter the signal handler. We are going to
257 // do some interesting stuff from here.
258 // TODO(satorux): We might want to set timeout here using alarm(), but
259 // mixing alarm() and sleep() can be a bad idea.
261 // First dump time info.
264 // Get the program counter from ucontext.
265 void *pc = GetPC(ucontext);
266 DumpStackFrameInfo("PC: ", pc);
268 #ifdef HAVE_STACKTRACE
269 // Get the stack traces.
271 // +1 to exclude this function.
272 const int depth = GetStackTrace(stack, ARRAYSIZE(stack), 1);
273 DumpSignalInfo(signal_number, signal_info);
274 // Dump the stack traces.
275 for (int i = 0; i < depth; ++i) {
276 DumpStackFrameInfo(" ", stack[i]);
280 // *** TRANSITION ***
282 // BEFORE this point, all code must be async-termination-safe!
283 // (See WARNING above.)
285 // AFTER this point, we do unsafe things, like using LOG()!
286 // The process could be terminated or hung at any time. We try to
287 // do more useful things first and riskier things later.
289 // Flush the logs before we do anything in case 'anything'
291 FlushLogFilesUnsafe(0);
293 // Kill ourself by the default signal handler.
294 InvokeDefaultSignalHandler(signal_number);
299 void InstallFailureSignalHandler() {
300 // Build the sigaction struct.
301 struct sigaction sig_action = {}; // Zero-clear.
302 sigemptyset(&sig_action.sa_mask);
303 sig_action.sa_flags |= SA_SIGINFO;
304 sig_action.sa_sigaction = &FailureSignalHandler;
306 for (int i = 0; i < ARRAYSIZE(kFailureSignals); ++i) {
307 CHECK_ERR(sigaction(kFailureSignals[i].number, &sig_action, NULL));
311 void InstallFailureWriter(void (*writer)(const char* data, int size)) {
312 g_failure_writer = writer;
315 _END_GOOGLE_NAMESPACE_