| 1 | // **************************************************************************** |
| 2 | // Project: libguytools |
| 3 | // **************************************************************************** |
| 4 | // Programmer: Guy Voncken |
| 5 | // Police Grand-Ducale |
| 6 | // Service de Police Judiciaire |
| 7 | // Section Nouvelles Technologies |
| 8 | // **************************************************************************** |
| 9 | // Module: Signal handler with backtrace |
| 10 | // **************************************************************************** |
| 11 | |
| 12 | // Copyright 2008, 2009, 2010, 2011, 2012, 2013, 2014, 2015, 2016, 2017, |
| 13 | // 2018, 2019 |
| 14 | // Guy Voncken |
| 15 | // |
| 16 | // This file is part of libguytools. |
| 17 | // |
| 18 | // libguytools is free software: you can redistribute it and/or modify |
| 19 | // it under the terms of the GNU General Public License as published by |
| 20 | // the Free Software Foundation, either version 2 of the License, or |
| 21 | // (at your option) any later version. |
| 22 | // |
| 23 | // libguytools is distributed in the hope that it will be useful, |
| 24 | // but WITHOUT ANY WARRANTY; without even the implied warranty of |
| 25 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
| 26 | // GNU General Public License for more details. |
| 27 | // |
| 28 | // You should have received a copy of the GNU General Public License |
| 29 | // along with libguytools. If not, see <http://www.gnu.org/licenses/>. |
| 30 | |
| 31 | #include <stdarg.h> |
| 32 | #include <stdio.h> |
| 33 | #include <stdlib.h> |
| 34 | //#define __USE_GNU |
| 35 | #include <string.h> |
| 36 | #include <unistd.h> |
| 37 | //#define __USE_XOPEN |
| 38 | #include <signal.h> |
| 39 | #include <execinfo.h> |
| 40 | #include <pthread.h> |
| 41 | |
| 42 | #include "tooltypes.h" |
| 43 | #include "toolglobalid.h" |
| 44 | #include "toolsignal.h" |
| 45 | #include "toolerror.h" |
| 46 | |
| 47 | // ------------------------------------ |
| 48 | // Type definitions |
| 49 | // ------------------------------------ |
| 50 | |
| 51 | typedef struct |
| 52 | { |
| 53 | t_pToolSignalLogFn pLogFn; |
| 54 | t_pToolSignalHandler pSignalHandlerFn; |
| 55 | struct sigaction SignalActionDefault; |
| 56 | } t_ToolSignalLocal; |
| 57 | |
| 58 | |
| 59 | // ------------------------------------ |
| 60 | // Module variables |
| 61 | // ------------------------------------ |
| 62 | |
| 63 | static bool ToolSignalInitialised = false; |
| 64 | |
| 65 | static t_ToolSignalLocal ToolSignalLocal; |
| 66 | |
| 67 | // ------------------------------------ |
| 68 | // Log functions |
| 69 | // ------------------------------------ |
| 70 | |
| 71 | #pragma GCC diagnostic push |
| 72 | #pragma GCC diagnostic ignored "-Wformat-nonliteral" |
| 73 | static int ToolSignalLogEntry (bool Error, const char *pFileName, const char *pFunctionName, int LineNr, const char *pFormat, ...) |
| 74 | { |
| 75 | va_list VaList; |
| 76 | |
| 77 | va_start(VaList, pFormat); |
| 78 | if (ToolSignalLocal.pLogFn) |
| 79 | { |
| 80 | (*ToolSignalLocal.pLogFn)(Error, pthread_self(), pFileName, pFunctionName, LineNr, pFormat, VaList); |
| 81 | } |
| 82 | else |
| 83 | { |
| 84 | printf ("\n"); |
| 85 | vprintf (pFormat, VaList); |
| 86 | } |
| 87 | va_end(VaList); |
| 88 | |
| 89 | return NO_ERROR; |
| 90 | } |
| 91 | #pragma GCC diagnostic pop |
| 92 | |
| 93 | // ------------------------------------ |
| 94 | // Main functions |
| 95 | // ------------------------------------ |
| 96 | |
| 97 | static void ToolSignalStandardSet (sigset_t *pSignalSet) |
| 98 | { |
| 99 | sigfillset (pSignalSet); // Add all known signals to set, except the ones listed below: |
| 100 | sigdelset (pSignalSet, SIGSEGV); // - handled by our backtrace function, see below |
| 101 | sigdelset (pSignalSet, SIGPIPE); // - which would cause problems in ceratin situations when our program deals with pipes |
| 102 | sigdelset (pSignalSet, SIGWINCH); // - emitted on window resize |
| 103 | sigdelset (pSignalSet, SIGCHLD); // - QProcess relies on receiving this one in order to know when a child process finishes |
| 104 | } // These settings will be valid for the current thread and all its children threads. That's the reason, why |
| 105 | // ToolSignalInit should be called in the application main thread before starting any other thread. |
| 106 | |
| 107 | static void *ToolSignalThread (void * /*p*/) |
| 108 | { |
| 109 | sigset_t SignalSet; |
| 110 | int Signal; |
| 111 | bool Exit; |
| 112 | char *pSignalName; |
| 113 | |
| 114 | ToolSignalLogEntry (false, __FFL__, "Signal guard thread started with id %d", getpid()); |
| 115 | |
| 116 | Exit = false; |
| 117 | while (!Exit) |
| 118 | { |
| 119 | ToolSignalStandardSet (&SignalSet); |
| 120 | sigwait (&SignalSet, &Signal); // wait for any signal in given set |
| 121 | |
| 122 | // when we get here, we've caught a signal |
| 123 | // --------------------------------------- |
| 124 | pSignalName = strsignal(Signal); |
| 125 | ToolSignalLogEntry (true, __FFL__, "Thread (%d-%d): Caught signal: %s", getpid(), pthread_self(), pSignalName); |
| 126 | if (ToolSignalLocal.pSignalHandlerFn) |
| 127 | (*ToolSignalLocal.pSignalHandlerFn) (Signal); |
| 128 | |
| 129 | switch (Signal) |
| 130 | { |
| 131 | case SIGTERM: |
| 132 | case SIGINT : Exit = true; break; |
| 133 | default: break; |
| 134 | } |
| 135 | } |
| 136 | ToolSignalLogEntry (true, __FFL__, "Stopping signal guard thread."); |
| 137 | return nullptr; |
| 138 | } |
| 139 | |
| 140 | // ToolSignalBacktraceHandler is called by any |
| 141 | // thread in the program causing a segment violation. |
| 142 | |
| 143 | #pragma GCC diagnostic push |
| 144 | #ifdef Q_CREATOR_RUN |
| 145 | #pragma GCC diagnostic ignored "-Wdisabled-macro-expansion" |
| 146 | #endif |
| 147 | [[noreturn]] static void ToolSignalBacktraceHandler (int Signal, siginfo_t *pSignalInfo, void *pSecret) |
| 148 | { |
| 149 | const int TraceArrLen = 50; |
| 150 | char **ppMessages; |
| 151 | void *TraceArr[TraceArrLen]; |
| 152 | int TraceSize; |
| 153 | int i; |
| 154 | static int RecursiveCallDetection = 0; |
| 155 | |
| 156 | /* Code below is no longer needed. According to tests on amd64 and i386 on Ubuntu 14.04, the address of the |
| 157 | place the where exception occured nowadays is correctly included in the array data returned by backtrace(). |
| 158 | It thus seems to be no longer necessary to separately fetch and add the instruction pointer corresponding |
| 159 | to the segmentation fault. |
| 160 | This wasn't the case on older systems, see for example http://www.linuxjournal.com/article/6391?page=0,1 . |
| 161 | |
| 162 | void *pIP = nullptr; |
| 163 | |
| 164 | #if defined(__sparc__) |
| 165 | struct sigcontext* pSigContext = (struct sigcontext*) pSecret; |
| 166 | #if __WORDSIZE == 64 |
| 167 | pIP = (void*) pSigContext->sigc_regs.tpc ; |
| 168 | #else |
| 169 | pIP = (void*) pSigContext->si_regs.pc ; |
| 170 | #endif |
| 171 | #else |
| 172 | ucontext_t* pUContext = (ucontext_t*) pSecret; |
| 173 | #if defined(__i386__) |
| 174 | pIP = (void*) pUContext->uc_mcontext.gregs[REG_EIP]; |
| 175 | #elif defined(__x86_64__) |
| 176 | pIP = (void*) pUContext->uc_mcontext.gregs[REG_RIP]; |
| 177 | #elif defined(__hppa__) |
| 178 | pIP = (void*) pUContext->uc_mcontext.sc_iaoq[0] & ~0x3UL; |
| 179 | #elif (defined (__ppc__)) || (defined (__powerpc__)) |
| 180 | pIP = (void*) pUContext->uc_mcontext.regs->nip; |
| 181 | #elif defined(__arm__) |
| 182 | pIP = (void*) pUContext->uc_mcontext.arm_pc; |
| 183 | #elif defined(__aarch64__) |
| 184 | pIP = (void*) pUContext->uc_mcontext.pc; |
| 185 | #endif |
| 186 | #endif |
| 187 | */ |
| 188 | |
| 189 | RecursiveCallDetection++; |
| 190 | switch (RecursiveCallDetection) |
| 191 | { |
| 192 | case 1: |
| 193 | ppMessages = nullptr; |
| 194 | |
| 195 | ToolSignalLogEntry (true, __FFL__, "----------------------------------------------------------------------"); |
| 196 | if (Signal == SIGSEGV) |
| 197 | { |
| 198 | ToolSignalLogEntry (true, __FFL__, "Thread (%d-%d): Got signal '%s' (%d), faulty address is %p" /*, "from %p" */, // See remarks above |
| 199 | getpid(), pthread_self(), strsignal(Signal), Signal, |
| 200 | pSignalInfo->si_addr /*, pIP*/); |
| 201 | } |
| 202 | else |
| 203 | { |
| 204 | ToolSignalLogEntry (true, __FFL__, "Thread (%d-%d): Got signal '%s' (%d) -- strange, function should only be called on SIGSEGV.", |
| 205 | getpid(), pthread_self(), strsignal(Signal), Signal); |
| 206 | } |
| 207 | TraceSize = backtrace (TraceArr, TraceArrLen); |
| 208 | /* TraceArr[1] = pIP; */ // See remarks above |
| 209 | ppMessages = backtrace_symbols (TraceArr, TraceSize); |
| 210 | |
| 211 | ToolSignalLogEntry (true, __FFL__, "Backtrace execution path"); |
| 212 | ToolSignalLogEntry (true, __FFL__, "The first two entries are normally related to the signal handler."); |
| 213 | ToolSignalLogEntry (true, __FFL__, "The faulty code generally is referenced by the 3rd line in the listing below."); |
| 214 | for (i=0; i<TraceSize; ++i) |
| 215 | ToolSignalLogEntry (true, __FFL__, "[Backtrace] %s", ppMessages[i]); |
| 216 | |
| 217 | if (ToolSignalLocal.pSignalHandlerFn) |
| 218 | (*ToolSignalLocal.pSignalHandlerFn) (SIGSEGV); |
| 219 | |
| 220 | ToolSignalLogEntry (true, __FFL__, "Calling original SIGSEGV handler"); |
| 221 | ToolSignalLogEntry (true, __FFL__, "----------------------------------------------------------------------"); |
| 222 | sigaction (SIGSEGV, &ToolSignalLocal.SignalActionDefault, nullptr); // Switch back to original handler, if ever another exception |
| 223 | (*ToolSignalLocal.SignalActionDefault.sa_sigaction) (Signal, pSignalInfo, pSecret); // occurs (nobody knows, what the original handler is doing..) |
| 224 | break; |
| 225 | |
| 226 | case 2: |
| 227 | ToolSignalLogEntry (true, __FFL__, "Recursive call of backtrace handler detected, calling original handler now."); |
| 228 | sigaction (SIGSEGV, &ToolSignalLocal.SignalActionDefault, nullptr); // Switch back to original handler, if ever another esception |
| 229 | (*ToolSignalLocal.SignalActionDefault.sa_sigaction) (Signal, pSignalInfo, pSecret); // occurs (nobody knows, what the original handler is doing..) |
| 230 | break; |
| 231 | |
| 232 | default: |
| 233 | ToolSignalLogEntry (true, __FFL__, "Recursive call of backtrace handler detected, iteration %d. Exiting now.", RecursiveCallDetection); |
| 234 | break; |
| 235 | } |
| 236 | exit (10); |
| 237 | } |
| 238 | #pragma GCC diagnostic pop |
| 239 | |
| 240 | // ------------------------------ |
| 241 | // Module initialisation |
| 242 | // ------------------------------ |
| 243 | |
| 244 | #pragma GCC diagnostic push |
| 245 | #ifdef Q_CREATOR_RUN |
| 246 | #pragma GCC diagnostic ignored "-Wdisabled-macro-expansion" |
| 247 | #endif |
| 248 | int ToolSignalInit (t_pToolSignalLogFn pFnLog, t_pToolSignalHandler pFnSig, unsigned long long *pThreadId) |
| 249 | { |
| 250 | struct sigaction SignalAction; |
| 251 | sigset_t SignalSet; |
| 252 | int StartRc; |
| 253 | |
| 254 | if (ToolSignalInitialised) |
| 255 | return ERROR_TOOLSIGNAL_ALREADY_INITIALISED; |
| 256 | |
| 257 | TOOL_CHK (TOOL_ERROR_REGISTER_CODE (ERROR_BASE_TOOL_SIGNAL)) |
| 258 | TOOL_CHK (TOOL_ERROR_REGISTER_CODE (ERROR_TOOLSIGNAL_ALREADY_INITIALISED)) |
| 259 | TOOL_CHK (TOOL_ERROR_REGISTER_CODE (ERROR_TOOLSIGNAL_STARTTHREAD_FAILED)) |
| 260 | |
| 261 | ToolSignalLocal.pLogFn = pFnLog; |
| 262 | ToolSignalLocal.pSignalHandlerFn = pFnSig; |
| 263 | |
| 264 | // Install segment violation signal handler |
| 265 | // ---------------------------------------- |
| 266 | sigemptyset (&SignalAction.sa_mask); |
| 267 | SignalAction.sa_sigaction = ToolSignalBacktraceHandler; // ToolSignalBacktraceSignalHandler will be called |
| 268 | SignalAction.sa_flags = SA_RESTART | SA_SIGINFO; // by any thread having a segment violation |
| 269 | sigaction (SIGSEGV, &SignalAction, &ToolSignalLocal.SignalActionDefault); |
| 270 | if (pThreadId) |
| 271 | *pThreadId = pthread_self(); |
| 272 | |
| 273 | // Set all other signals to "block" |
| 274 | // -------------------------------- |
| 275 | ToolSignalStandardSet (&SignalSet); |
| 276 | pthread_sigmask (SIG_BLOCK, &SignalSet, nullptr); // reason, why ToolSignalInit should be called in the application main thread before |
| 277 | |
| 278 | // Start the signal handler thread |
| 279 | // ------------------------------- |
| 280 | pthread_t ThreadStruct; |
| 281 | |
| 282 | StartRc = pthread_create (&ThreadStruct, nullptr, ToolSignalThread, nullptr); |
| 283 | if (StartRc != 0) |
| 284 | return ERROR_TOOLSIGNAL_STARTTHREAD_FAILED; |
| 285 | |
| 286 | ToolSignalInitialised = true; |
| 287 | |
| 288 | return NO_ERROR; |
| 289 | } |
| 290 | #pragma GCC diagnostic pop |
| 291 | |
| 292 | int ToolSignalDeInit (void) |
| 293 | { |
| 294 | sigset_t SignalSet; |
| 295 | |
| 296 | if (!ToolSignalInitialised) |
| 297 | return ERROR_TOOLSIGNAL_NOT_INITIALISED; |
| 298 | |
| 299 | // Unblock the signals again |
| 300 | // ------------------------- |
| 301 | ToolSignalStandardSet (&SignalSet); // Unblocking is only done for this thread; signals in child |
| 302 | pthread_sigmask (SIG_UNBLOCK, &SignalSet, nullptr); // threads started from this thread remain blocked. |
| 303 | |
| 304 | // Switch back to default SIGSEV signal handler |
| 305 | // -------------------------------------------- |
| 306 | sigaction (SIGSEGV, &ToolSignalLocal.SignalActionDefault, nullptr); |
| 307 | |
| 308 | ToolSignalInitialised = false; |
| 309 | return NO_ERROR; |
| 310 | } |
| 311 |