58f197e9f99f4daba83b18ee97c0c7da830f7d52
[platform/upstream/glog.git] / src / signalhandler.cc
1 // Copyright 2008 Google Inc. All Rights Reserved.
2 // Author: Satoru Takabayashi
3 //
4 // Implementation of InstallFailureSignalHandler().
5
6 #include "utilities.h"
7 #include "stacktrace.h"
8 #include "symbolize.h"
9 #include "glog/logging.h"
10
11 #include <signal.h>
12 #include <time.h>
13 #ifdef HAVE_UCONTEXT_H
14 # include <ucontext.h>
15 #endif
16 #include <algorithm>
17
18 _START_GOOGLE_NAMESPACE_
19
20 namespace {
21
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.
25 //
26 // The list should be synced with the comment in signalhandler.h.
27 const struct {
28   int number;
29   const char *name;
30 } kFailureSignals[] = {
31   { SIGSEGV, "SIGSEGV" },
32   { SIGILL, "SIGILL" },
33   { SIGFPE, "SIGFPE" },
34   { SIGABRT, "SIGABRT" },
35   { SIGBUS, "SIGBUS" },
36   { SIGTERM, "SIGTERM" },
37 };
38
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;
45   }
46 #endif
47   return NULL;
48 }
49
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 {
53  public:
54   MinimalFormatter(char *buffer, int size)
55       : buffer_(buffer),
56         cursor_(buffer),
57         end_(buffer + size) {
58   }
59
60   // Returns the number of bytes written in the buffer.
61   int num_bytes_written() const { return cursor_ - buffer_; }
62
63   // Appends string from "str" and updates the internal cursor.
64   void AppendString(const char* str) {
65     int i = 0;
66     while (str[i] != '\0' && cursor_ + i < end_) {
67       cursor_[i] = str[i];
68       ++i;
69     }
70     cursor_ += i;
71   }
72
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) {
76     int i = 0;
77     while (cursor_ + i < end_) {
78       const int tmp = number % radix;
79       number /= radix;
80       cursor_[i] = (tmp < 10 ? '0' + tmp : 'a' + tmp - 10);
81       ++i;
82       if (number == 0) {
83         break;
84       }
85     }
86     // Reverse the bytes written.
87     std::reverse(cursor_, cursor_ + i);
88     cursor_ += i;
89   }
90
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_;
95     AppendString("0x");
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;
103     }
104   }
105
106  private:
107   char *buffer_;
108   char *cursor_;
109   const char * const end_;
110 };
111
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);
115 }
116
117 // The writer function can be changed by InstallFailureWriter().
118 void (*g_failure_writer)(const char* data, int size) = WriteToStderr;
119
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());
133 }
134
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;
142     }
143   }
144
145   char buf[256];  // Big enough for signal info.
146   MinimalFormatter formatter(buf, sizeof(buf));
147
148   formatter.AppendString("*** ");
149   if (signal_name) {
150     formatter.AppendString(signal_name);
151   } else {
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);
156   }
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.
171 #ifdef OS_LINUX
172   formatter.AppendString("from PID ");
173   formatter.AppendUint64(siginfo->si_pid, 10);
174   formatter.AppendString("; ");
175 #endif
176   formatter.AppendString("stack trace: ***\n");
177   g_failure_writer(buf, formatter.num_bytes_written());
178 }
179
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
186   // next function.
187   if (Symbolize(reinterpret_cast<char *>(pc) - 1,
188                 symbolized, sizeof(symbolized))) {
189     symbol = symbolized;
190   }
191
192   char buf[1024];  // Big enough for stack frame info.
193   MinimalFormatter formatter(buf, sizeof(buf));
194
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());
203 }
204
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);
212 }
213
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;
219
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,
224                           void *ucontext) {
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.
228
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),
241           &my_thread_id);
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);
249     }
250     // Another thread is dumping stuff.  Let's wait until that thread
251     // finishes the job and kills the process.
252     while (true) {
253       sleep(1);
254     }
255   }
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.
260
261   // First dump time info.
262   DumpTimeInfo();
263
264   // Get the program counter from ucontext.
265   void *pc = GetPC(ucontext);
266   DumpStackFrameInfo("PC: ", pc);
267
268 #ifdef HAVE_STACKTRACE
269   // Get the stack traces.
270   void *stack[32];
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]);
277   }
278 #endif
279
280   // *** TRANSITION ***
281   //
282   // BEFORE this point, all code must be async-termination-safe!
283   // (See WARNING above.)
284   //
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.
288
289   // Flush the logs before we do anything in case 'anything'
290   // causes problems.
291   FlushLogFilesUnsafe(0);
292
293   // Kill ourself by the default signal handler.
294   InvokeDefaultSignalHandler(signal_number);
295 }
296
297 }  // namespace
298
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;
305
306   for (int i = 0; i < ARRAYSIZE(kFailureSignals); ++i) {
307     CHECK_ERR(sigaction(kFailureSignals[i].number, &sig_action, NULL));
308   }
309 }
310
311 void InstallFailureWriter(void (*writer)(const char* data, int size)) {
312   g_failure_writer = writer;
313 }
314
315 _END_GOOGLE_NAMESPACE_