1//===- Signals.cpp - Generic Unix Signals Implementation -----*- C++ -*-===// 2// 3// The LLVM Compiler Infrastructure 4// 5// This file is distributed under the University of Illinois Open Source 6// License. See LICENSE.TXT for details. 7// 8//===----------------------------------------------------------------------===// 9// 10// This file defines some helpful functions for dealing with the possibility of 11// Unix signals occurring while your program is running. 12// 13//===----------------------------------------------------------------------===// 14 15#include "Unix.h" 16#include "llvm/ADT/STLExtras.h" 17#include "llvm/Support/Mutex.h" 18#include <algorithm> 19#include <string> 20#include <vector> 21#if HAVE_EXECINFO_H 22# include <execinfo.h> // For backtrace(). 23#endif 24#if HAVE_SIGNAL_H 25#include <signal.h> 26#endif 27#if HAVE_SYS_STAT_H 28#include <sys/stat.h> 29#endif 30#if HAVE_CXXABI_H 31#include <cxxabi.h> 32#endif 33#if HAVE_DLFCN_H 34#include <dlfcn.h> 35#endif 36#if HAVE_MACH_MACH_H 37#include <mach/mach.h> 38#endif 39 40using namespace llvm; 41 42static RETSIGTYPE SignalHandler(int Sig); // defined below. 43 44static SmartMutex<true> SignalsMutex; 45 46/// InterruptFunction - The function to call if ctrl-c is pressed. 47static void (*InterruptFunction)() = 0; 48 49static std::vector<std::string> FilesToRemove; 50static std::vector<std::pair<void(*)(void*), void*> > CallBacksToRun; 51 52// IntSigs - Signals that represent requested termination. There's no bug 53// or failure, or if there is, it's not our direct responsibility. For whatever 54// reason, our continued execution is no longer desirable. 55static const int IntSigs[] = { 56 SIGHUP, SIGINT, SIGPIPE, SIGTERM, SIGUSR1, SIGUSR2 57}; 58static const int *const IntSigsEnd = 59 IntSigs + sizeof(IntSigs) / sizeof(IntSigs[0]); 60 61// KillSigs - Signals that represent that we have a bug, and our prompt 62// termination has been ordered. 63static const int KillSigs[] = { 64 SIGILL, SIGTRAP, SIGABRT, SIGFPE, SIGBUS, SIGSEGV, SIGQUIT 65#ifdef SIGSYS 66 , SIGSYS 67#endif 68#ifdef SIGXCPU 69 , SIGXCPU 70#endif 71#ifdef SIGXFSZ 72 , SIGXFSZ 73#endif 74#ifdef SIGEMT 75 , SIGEMT 76#endif 77}; 78static const int *const KillSigsEnd = 79 KillSigs + sizeof(KillSigs) / sizeof(KillSigs[0]); 80 81static unsigned NumRegisteredSignals = 0; 82static struct { 83 struct sigaction SA; 84 int SigNo; 85} RegisteredSignalInfo[(sizeof(IntSigs)+sizeof(KillSigs))/sizeof(KillSigs[0])]; 86 87 88static void RegisterHandler(int Signal) { 89 assert(NumRegisteredSignals < 90 sizeof(RegisteredSignalInfo)/sizeof(RegisteredSignalInfo[0]) && 91 "Out of space for signal handlers!"); 92 93 struct sigaction NewHandler; 94 95 NewHandler.sa_handler = SignalHandler; 96 NewHandler.sa_flags = SA_NODEFER|SA_RESETHAND; 97 sigemptyset(&NewHandler.sa_mask); 98 99 // Install the new handler, save the old one in RegisteredSignalInfo. 100 sigaction(Signal, &NewHandler, 101 &RegisteredSignalInfo[NumRegisteredSignals].SA); 102 RegisteredSignalInfo[NumRegisteredSignals].SigNo = Signal; 103 ++NumRegisteredSignals; 104} 105 106static void RegisterHandlers() { 107 // If the handlers are already registered, we're done. 108 if (NumRegisteredSignals != 0) return; 109 110 std::for_each(IntSigs, IntSigsEnd, RegisterHandler); 111 std::for_each(KillSigs, KillSigsEnd, RegisterHandler); 112} 113 114static void UnregisterHandlers() { 115 // Restore all of the signal handlers to how they were before we showed up. 116 for (unsigned i = 0, e = NumRegisteredSignals; i != e; ++i) 117 sigaction(RegisteredSignalInfo[i].SigNo, 118 &RegisteredSignalInfo[i].SA, 0); 119 NumRegisteredSignals = 0; 120} 121 122 123/// RemoveFilesToRemove - Process the FilesToRemove list. This function 124/// should be called with the SignalsMutex lock held. 125/// NB: This must be an async signal safe function. It cannot allocate or free 126/// memory, even in debug builds. 127static void RemoveFilesToRemove() { 128 // We avoid iterators in case of debug iterators that allocate or release 129 // memory. 130 for (unsigned i = 0, e = FilesToRemove.size(); i != e; ++i) { 131 // We rely on a std::string implementation for which repeated calls to 132 // 'c_str()' don't allocate memory. We pre-call 'c_str()' on all of these 133 // strings to try to ensure this is safe. 134 const char *path = FilesToRemove[i].c_str(); 135 136 // Get the status so we can determine if it's a file or directory. If we 137 // can't stat the file, ignore it. 138 struct stat buf; 139 if (stat(path, &buf) != 0) 140 continue; 141 142 // If this is not a regular file, ignore it. We want to prevent removal of 143 // special files like /dev/null, even if the compiler is being run with the 144 // super-user permissions. 145 if (!S_ISREG(buf.st_mode)) 146 continue; 147 148 // Otherwise, remove the file. We ignore any errors here as there is nothing 149 // else we can do. 150 unlink(path); 151 } 152} 153 154// SignalHandler - The signal handler that runs. 155static RETSIGTYPE SignalHandler(int Sig) { 156 // Restore the signal behavior to default, so that the program actually 157 // crashes when we return and the signal reissues. This also ensures that if 158 // we crash in our signal handler that the program will terminate immediately 159 // instead of recursing in the signal handler. 160 UnregisterHandlers(); 161 162 // Unmask all potentially blocked kill signals. 163 sigset_t SigMask; 164 sigfillset(&SigMask); 165 sigprocmask(SIG_UNBLOCK, &SigMask, 0); 166 167 SignalsMutex.acquire(); 168 RemoveFilesToRemove(); 169 170 if (std::find(IntSigs, IntSigsEnd, Sig) != IntSigsEnd) { 171 if (InterruptFunction) { 172 void (*IF)() = InterruptFunction; 173 SignalsMutex.release(); 174 InterruptFunction = 0; 175 IF(); // run the interrupt function. 176 return; 177 } 178 179 SignalsMutex.release(); 180 raise(Sig); // Execute the default handler. 181 return; 182 } 183 184 SignalsMutex.release(); 185 186 // Otherwise if it is a fault (like SEGV) run any handler. 187 for (unsigned i = 0, e = CallBacksToRun.size(); i != e; ++i) 188 CallBacksToRun[i].first(CallBacksToRun[i].second); 189 190#ifdef __s390__ 191 // On S/390, certain signals are delivered with PSW Address pointing to 192 // *after* the faulting instruction. Simply returning from the signal 193 // handler would continue execution after that point, instead of 194 // re-raising the signal. Raise the signal manually in those cases. 195 if (Sig == SIGILL || Sig == SIGFPE || Sig == SIGTRAP) 196 raise(Sig); 197#endif 198} 199 200void llvm::sys::RunInterruptHandlers() { 201 SignalsMutex.acquire(); 202 RemoveFilesToRemove(); 203 SignalsMutex.release(); 204} 205 206void llvm::sys::SetInterruptFunction(void (*IF)()) { 207 SignalsMutex.acquire(); 208 InterruptFunction = IF; 209 SignalsMutex.release(); 210 RegisterHandlers(); 211} 212 213// RemoveFileOnSignal - The public API 214bool llvm::sys::RemoveFileOnSignal(const sys::Path &Filename, 215 std::string* ErrMsg) { 216 SignalsMutex.acquire(); 217 std::string *OldPtr = FilesToRemove.empty() ? 0 : &FilesToRemove[0]; 218 FilesToRemove.push_back(Filename.str()); 219 220 // We want to call 'c_str()' on every std::string in this vector so that if 221 // the underlying implementation requires a re-allocation, it happens here 222 // rather than inside of the signal handler. If we see the vector grow, we 223 // have to call it on every entry. If it remains in place, we only need to 224 // call it on the latest one. 225 if (OldPtr == &FilesToRemove[0]) 226 FilesToRemove.back().c_str(); 227 else 228 for (unsigned i = 0, e = FilesToRemove.size(); i != e; ++i) 229 FilesToRemove[i].c_str(); 230 231 SignalsMutex.release(); 232 233 RegisterHandlers(); 234 return false; 235} 236 237// DontRemoveFileOnSignal - The public API 238void llvm::sys::DontRemoveFileOnSignal(const sys::Path &Filename) { 239 SignalsMutex.acquire(); 240 std::vector<std::string>::reverse_iterator RI = 241 std::find(FilesToRemove.rbegin(), FilesToRemove.rend(), Filename.str()); 242 std::vector<std::string>::iterator I = FilesToRemove.end(); 243 if (RI != FilesToRemove.rend()) 244 I = FilesToRemove.erase(RI.base()-1); 245 246 // We need to call c_str() on every element which would have been moved by 247 // the erase. These elements, in a C++98 implementation where c_str() 248 // requires a reallocation on the first call may have had the call to c_str() 249 // made on insertion become invalid by being copied down an element. 250 for (std::vector<std::string>::iterator E = FilesToRemove.end(); I != E; ++I) 251 I->c_str(); 252 253 SignalsMutex.release(); 254} 255 256/// AddSignalHandler - Add a function to be called when a signal is delivered 257/// to the process. The handler can have a cookie passed to it to identify 258/// what instance of the handler it is. 259void llvm::sys::AddSignalHandler(void (*FnPtr)(void *), void *Cookie) { 260 CallBacksToRun.push_back(std::make_pair(FnPtr, Cookie)); 261 RegisterHandlers(); 262} 263 264 265// PrintStackTrace - In the case of a program crash or fault, print out a stack 266// trace so that the user has an indication of why and where we died. 267// 268// On glibc systems we have the 'backtrace' function, which works nicely, but 269// doesn't demangle symbols. 270void llvm::sys::PrintStackTrace(FILE *FD) { 271#if defined(HAVE_BACKTRACE) && defined(ENABLE_BACKTRACES) 272 static void* StackTrace[256]; 273 // Use backtrace() to output a backtrace on Linux systems with glibc. 274 int depth = backtrace(StackTrace, 275 static_cast<int>(array_lengthof(StackTrace))); 276#if HAVE_DLFCN_H && __GNUG__ 277 int width = 0; 278 for (int i = 0; i < depth; ++i) { 279 Dl_info dlinfo; 280 dladdr(StackTrace[i], &dlinfo); 281 const char* name = strrchr(dlinfo.dli_fname, '/'); 282 283 int nwidth; 284 if (name == NULL) nwidth = strlen(dlinfo.dli_fname); 285 else nwidth = strlen(name) - 1; 286 287 if (nwidth > width) width = nwidth; 288 } 289 290 for (int i = 0; i < depth; ++i) { 291 Dl_info dlinfo; 292 dladdr(StackTrace[i], &dlinfo); 293 294 fprintf(FD, "%-2d", i); 295 296 const char* name = strrchr(dlinfo.dli_fname, '/'); 297 if (name == NULL) fprintf(FD, " %-*s", width, dlinfo.dli_fname); 298 else fprintf(FD, " %-*s", width, name+1); 299 300 fprintf(FD, " %#0*lx", 301 (int)(sizeof(void*) * 2) + 2, (unsigned long)StackTrace[i]); 302 303 if (dlinfo.dli_sname != NULL) { 304 fputc(' ', FD); 305# if HAVE_CXXABI_H 306 int res; 307 char* d = abi::__cxa_demangle(dlinfo.dli_sname, NULL, NULL, &res); 308# else 309 char* d = NULL; 310# endif 311 if (d == NULL) fputs(dlinfo.dli_sname, FD); 312 else fputs(d, FD); 313 free(d); 314 315 // FIXME: When we move to C++11, use %t length modifier. It's not in 316 // C++03 and causes gcc to issue warnings. Losing the upper 32 bits of 317 // the stack offset for a stack dump isn't likely to cause any problems. 318 fprintf(FD, " + %u",(unsigned)((char*)StackTrace[i]- 319 (char*)dlinfo.dli_saddr)); 320 } 321 fputc('\n', FD); 322 } 323#else 324 backtrace_symbols_fd(StackTrace, depth, STDERR_FILENO); 325#endif 326#endif 327} 328 329static void PrintStackTraceSignalHandler(void *) { 330 PrintStackTrace(stderr); 331} 332 333/// PrintStackTraceOnErrorSignal - When an error signal (such as SIGABRT or 334/// SIGSEGV) is delivered to the process, print a stack trace and then exit. 335void llvm::sys::PrintStackTraceOnErrorSignal() { 336 AddSignalHandler(PrintStackTraceSignalHandler, 0); 337 338#if defined(__APPLE__) 339 // Environment variable to disable any kind of crash dialog. 340 if (getenv("LLVM_DISABLE_CRASH_REPORT")) { 341 mach_port_t self = mach_task_self(); 342 343 exception_mask_t mask = EXC_MASK_CRASH; 344 345 kern_return_t ret = task_set_exception_ports(self, 346 mask, 347 MACH_PORT_NULL, 348 EXCEPTION_STATE_IDENTITY | MACH_EXCEPTION_CODES, 349 THREAD_STATE_NONE); 350 (void)ret; 351 } 352#endif 353} 354 355 356/***/ 357 358// On Darwin, raise sends a signal to the main thread instead of the current 359// thread. This has the unfortunate effect that assert() and abort() will end up 360// bypassing our crash recovery attempts. We work around this for anything in 361// the same linkage unit by just defining our own versions of the assert handler 362// and abort. 363 364#ifdef __APPLE__ 365 366#include <signal.h> 367#include <pthread.h> 368 369int raise(int sig) { 370 return pthread_kill(pthread_self(), sig); 371} 372 373void __assert_rtn(const char *func, 374 const char *file, 375 int line, 376 const char *expr) { 377 if (func) 378 fprintf(stderr, "Assertion failed: (%s), function %s, file %s, line %d.\n", 379 expr, func, file, line); 380 else 381 fprintf(stderr, "Assertion failed: (%s), file %s, line %d.\n", 382 expr, file, line); 383 abort(); 384} 385 386void abort() { 387 raise(SIGABRT); 388 usleep(1000); 389 __builtin_trap(); 390} 391 392#endif 393