1 // Copyright (c) 2008, Google Inc.
2 // All rights reserved.
4 // Redistribution and use in source and binary forms, with or without
5 // modification, are permitted provided that the following conditions are
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
11 // copyright notice, this list of conditions and the following disclaimer
12 // in the documentation and/or other materials provided with the
14 // * Neither the name of Google Inc. nor the names of its
15 // contributors may be used to endorse or promote products derived from
16 // this software without specific prior written permission.
18 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
30 // Author: Satoru Takabayashi
32 // Implementation of InstallFailureSignalHandler().
34 #include "utilities.h"
35 #include "stacktrace.h"
36 #include "symbolize.h"
37 #include "glog/logging.h"
41 #ifdef HAVE_UCONTEXT_H
42 # include <ucontext.h>
46 _START_GOOGLE_NAMESPACE_
50 // We'll install the failure signal handler for these signals. We could
51 // use strsignal() to get signal names, but we don't use it to avoid
52 // introducing yet another #ifdef complication.
54 // The list should be synced with the comment in signalhandler.h.
58 } kFailureSignals[] = {
59 { SIGSEGV, "SIGSEGV" },
62 { SIGABRT, "SIGABRT" },
64 { SIGTERM, "SIGTERM" },
67 // Returns the program counter from signal context, NULL if unknown.
68 void* GetPC(void* ucontext_in_void) {
69 #if defined(HAVE_UCONTEXT_H) && defined(PC_FROM_UCONTEXT)
70 if (ucontext_in_void != NULL) {
71 ucontext_t *context = reinterpret_cast<ucontext_t *>(ucontext_in_void);
72 return (void*)context->PC_FROM_UCONTEXT;
78 // The class is used for formatting error messages. We don't use printf()
79 // as it's not async signal safe.
80 class MinimalFormatter {
82 MinimalFormatter(char *buffer, int size)
88 // Returns the number of bytes written in the buffer.
89 int num_bytes_written() const { return cursor_ - buffer_; }
91 // Appends string from "str" and updates the internal cursor.
92 void AppendString(const char* str) {
94 while (str[i] != '\0' && cursor_ + i < end_) {
101 // Formats "number" in "radix" and updates the internal cursor.
102 // Lowercase letters are used for 'a' - 'z'.
103 void AppendUint64(uint64 number, int radix) {
105 while (cursor_ + i < end_) {
106 const int tmp = number % radix;
108 cursor_[i] = (tmp < 10 ? '0' + tmp : 'a' + tmp - 10);
114 // Reverse the bytes written.
115 std::reverse(cursor_, cursor_ + i);
119 // Formats "number" as hexadecimal number, and updates the internal
120 // cursor. Padding will be added in front if needed.
121 void AppendHexWithPadding(uint64 number, int width) {
122 char* start = cursor_;
124 AppendUint64(number, 16);
125 // Move to right and add padding in front if needed.
126 if (cursor_ < start + width) {
127 const int64 delta = start + width - cursor_;
128 std::copy(start, cursor_, start + delta);
129 std::fill(start, start + delta, ' ');
130 cursor_ = start + width;
137 const char * const end_;
140 // Writes the given data with the size to the standard error.
141 void WriteToStderr(const char* data, int size) {
142 write(STDERR_FILENO, data, size);
145 // The writer function can be changed by InstallFailureWriter().
146 void (*g_failure_writer)(const char* data, int size) = WriteToStderr;
148 // Dumps time information. We don't dump human-readable time information
149 // as localtime() is not guaranteed to be async signal safe.
150 void DumpTimeInfo() {
151 time_t time_in_sec = time(NULL);
152 char buf[256]; // Big enough for time info.
153 MinimalFormatter formatter(buf, sizeof(buf));
154 formatter.AppendString("*** Aborted at ");
155 formatter.AppendUint64(time_in_sec, 10);
156 formatter.AppendString(" (unix time)");
157 formatter.AppendString(" try \"date -d @");
158 formatter.AppendUint64(time_in_sec, 10);
159 formatter.AppendString("\" if you are using GNU date ***\n");
160 g_failure_writer(buf, formatter.num_bytes_written());
163 // Dumps information about the signal to STDERR.
164 void DumpSignalInfo(int signal_number, siginfo_t *siginfo) {
165 // Get the signal name.
166 const char* signal_name = NULL;
167 for (int i = 0; i < ARRAYSIZE(kFailureSignals); ++i) {
168 if (signal_number == kFailureSignals[i].number) {
169 signal_name = kFailureSignals[i].name;
173 char buf[256]; // Big enough for signal info.
174 MinimalFormatter formatter(buf, sizeof(buf));
176 formatter.AppendString("*** ");
178 formatter.AppendString(signal_name);
180 // Use the signal number if the name is unknown. The signal name
181 // should be known, but just in case.
182 formatter.AppendString("Signal ");
183 formatter.AppendUint64(signal_number, 10);
185 formatter.AppendString(" (@0x");
186 formatter.AppendUint64(reinterpret_cast<uintptr_t>(siginfo->si_addr), 16);
187 formatter.AppendString(")");
188 formatter.AppendString(" received by PID ");
189 formatter.AppendUint64(getpid(), 10);
190 formatter.AppendString(" (TID 0x");
191 // We assume pthread_t is an integral number or a pointer, rather
192 // than a complex struct. In some environments, pthread_self()
193 // returns an uint64 but in some other environments pthread_self()
194 // returns a pointer. Hence we use C-style cast here, rather than
195 // reinterpret/static_cast, to support both types of environments.
196 formatter.AppendUint64((uintptr_t)pthread_self(), 16);
197 formatter.AppendString(") ");
198 // Only linux has the PID of the signal sender in si_pid.
200 formatter.AppendString("from PID ");
201 formatter.AppendUint64(siginfo->si_pid, 10);
202 formatter.AppendString("; ");
204 formatter.AppendString("stack trace: ***\n");
205 g_failure_writer(buf, formatter.num_bytes_written());
208 // Dumps information about the stack frame to STDERR.
209 void DumpStackFrameInfo(const char* prefix, void* pc) {
210 // Get the symbol name.
211 const char *symbol = "(unknown)";
212 char symbolized[1024]; // Big enough for a sane symbol.
213 // Symbolizes the previous address of pc because pc may be in the
215 if (Symbolize(reinterpret_cast<char *>(pc) - 1,
216 symbolized, sizeof(symbolized))) {
220 char buf[1024]; // Big enough for stack frame info.
221 MinimalFormatter formatter(buf, sizeof(buf));
223 formatter.AppendString(prefix);
224 formatter.AppendString("@ ");
225 const int width = 2 * sizeof(void*) + 2; // + 2 for "0x".
226 formatter.AppendHexWithPadding(reinterpret_cast<uintptr_t>(pc), width);
227 formatter.AppendString(" ");
228 formatter.AppendString(symbol);
229 formatter.AppendString("\n");
230 g_failure_writer(buf, formatter.num_bytes_written());
233 // Invoke the default signal handler.
234 void InvokeDefaultSignalHandler(int signal_number) {
235 struct sigaction sig_action;
236 memset(&sig_action, 0, sizeof(sig_action));
237 sigemptyset(&sig_action.sa_mask);
238 sig_action.sa_handler = SIG_DFL;
239 sigaction(signal_number, &sig_action, NULL);
240 kill(getpid(), signal_number);
243 // This variable is used for protecting FailureSignalHandler() from
244 // dumping stuff while another thread is doing it. Our policy is to let
245 // the first thread dump stuff and let other threads wait.
246 // See also comments in FailureSignalHandler().
247 static pthread_t* g_entered_thread_id_pointer = NULL;
249 // Dumps signal and stack frame information, and invokes the default
250 // signal handler once our job is done.
251 void FailureSignalHandler(int signal_number,
252 siginfo_t *signal_info,
254 // First check if we've already entered the function. We use an atomic
255 // compare and swap operation for platforms that support it. For other
256 // platforms, we use a naive method that could lead to a subtle race.
258 // We assume pthread_self() is async signal safe, though it's not
259 // officially guaranteed.
260 pthread_t my_thread_id = pthread_self();
261 // NOTE: We could simply use pthread_t rather than pthread_t* for this,
262 // if pthread_self() is guaranteed to return non-zero value for thread
263 // ids, but there is no such guarantee. We need to distinguish if the
264 // old value (value returned from __sync_val_compare_and_swap) is
265 // different from the original value (in this case NULL).
266 pthread_t* old_thread_id_pointer =
267 glog_internal_namespace_::sync_val_compare_and_swap(
268 &g_entered_thread_id_pointer,
269 static_cast<pthread_t*>(NULL),
271 if (old_thread_id_pointer != NULL) {
272 // We've already entered the signal handler. What should we do?
273 if (pthread_equal(my_thread_id, *g_entered_thread_id_pointer)) {
274 // It looks the current thread is reentering the signal handler.
275 // Something must be going wrong (maybe we are reentering by another
276 // type of signal?). Kill ourself by the default signal handler.
277 InvokeDefaultSignalHandler(signal_number);
279 // Another thread is dumping stuff. Let's wait until that thread
280 // finishes the job and kills the process.
285 // This is the first time we enter the signal handler. We are going to
286 // do some interesting stuff from here.
287 // TODO(satorux): We might want to set timeout here using alarm(), but
288 // mixing alarm() and sleep() can be a bad idea.
290 // First dump time info.
293 // Get the program counter from ucontext.
294 void *pc = GetPC(ucontext);
295 DumpStackFrameInfo("PC: ", pc);
297 #ifdef HAVE_STACKTRACE
298 // Get the stack traces.
300 // +1 to exclude this function.
301 const int depth = GetStackTrace(stack, ARRAYSIZE(stack), 1);
302 DumpSignalInfo(signal_number, signal_info);
303 // Dump the stack traces.
304 for (int i = 0; i < depth; ++i) {
305 DumpStackFrameInfo(" ", stack[i]);
309 // *** TRANSITION ***
311 // BEFORE this point, all code must be async-termination-safe!
312 // (See WARNING above.)
314 // AFTER this point, we do unsafe things, like using LOG()!
315 // The process could be terminated or hung at any time. We try to
316 // do more useful things first and riskier things later.
318 // Flush the logs before we do anything in case 'anything'
320 FlushLogFilesUnsafe(0);
322 // Kill ourself by the default signal handler.
323 InvokeDefaultSignalHandler(signal_number);
328 void InstallFailureSignalHandler() {
329 // Build the sigaction struct.
330 struct sigaction sig_action;
331 memset(&sig_action, 0, sizeof(sig_action));
332 sigemptyset(&sig_action.sa_mask);
333 sig_action.sa_flags |= SA_SIGINFO;
334 sig_action.sa_sigaction = &FailureSignalHandler;
336 for (int i = 0; i < ARRAYSIZE(kFailureSignals); ++i) {
337 CHECK_ERR(sigaction(kFailureSignals[i].number, &sig_action, NULL));
341 void InstallFailureWriter(void (*writer)(const char* data, int size)) {
342 g_failure_writer = writer;
345 _END_GOOGLE_NAMESPACE_