Signals.inc 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489
  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. #include "Unix.h"
  15. #include "llvm/ADT/STLExtras.h"
  16. #include "llvm/Demangle/Demangle.h"
  17. #include "llvm/Support/FileSystem.h"
  18. #include "llvm/Support/FileUtilities.h"
  19. #include "llvm/Support/Format.h"
  20. #include "llvm/Support/MemoryBuffer.h"
  21. #include "llvm/Support/Mutex.h"
  22. #include "llvm/Support/Program.h"
  23. #include "llvm/Support/UniqueLock.h"
  24. #include "llvm/Support/raw_ostream.h"
  25. #include <algorithm>
  26. #include <string>
  27. #ifdef HAVE_BACKTRACE
  28. # include BACKTRACE_HEADER // For backtrace().
  29. #endif
  30. #if HAVE_SIGNAL_H
  31. #include <signal.h>
  32. #endif
  33. #if HAVE_SYS_STAT_H
  34. #include <sys/stat.h>
  35. #endif
  36. #if HAVE_DLFCN_H
  37. #include <dlfcn.h>
  38. #endif
  39. #if HAVE_MACH_MACH_H
  40. #include <mach/mach.h>
  41. #endif
  42. #if HAVE_LINK_H
  43. #include <link.h>
  44. #endif
  45. #ifdef HAVE__UNWIND_BACKTRACE
  46. // FIXME: We should be able to use <unwind.h> for any target that has an
  47. // _Unwind_Backtrace function, but on FreeBSD the configure test passes
  48. // despite the function not existing, and on Android, <unwind.h> conflicts
  49. // with <link.h>.
  50. #ifdef __GLIBC__
  51. #include <unwind.h>
  52. #else
  53. #undef HAVE__UNWIND_BACKTRACE
  54. #endif
  55. #endif
  56. using namespace llvm;
  57. static RETSIGTYPE SignalHandler(int Sig); // defined below.
  58. static ManagedStatic<sys::SmartMutex<true> > SignalsMutex;
  59. /// InterruptFunction - The function to call if ctrl-c is pressed.
  60. static void (*InterruptFunction)() = nullptr;
  61. static ManagedStatic<std::vector<std::string>> FilesToRemove;
  62. static StringRef Argv0;
  63. // IntSigs - Signals that represent requested termination. There's no bug
  64. // or failure, or if there is, it's not our direct responsibility. For whatever
  65. // reason, our continued execution is no longer desirable.
  66. static const int IntSigs[] = {
  67. SIGHUP, SIGINT, SIGPIPE, SIGTERM, SIGUSR1, SIGUSR2
  68. };
  69. // KillSigs - Signals that represent that we have a bug, and our prompt
  70. // termination has been ordered.
  71. static const int KillSigs[] = {
  72. SIGILL, SIGTRAP, SIGABRT, SIGFPE, SIGBUS, SIGSEGV, SIGQUIT
  73. #ifdef SIGSYS
  74. , SIGSYS
  75. #endif
  76. #ifdef SIGXCPU
  77. , SIGXCPU
  78. #endif
  79. #ifdef SIGXFSZ
  80. , SIGXFSZ
  81. #endif
  82. #ifdef SIGEMT
  83. , SIGEMT
  84. #endif
  85. };
  86. static unsigned NumRegisteredSignals = 0;
  87. static struct {
  88. struct sigaction SA;
  89. int SigNo;
  90. } RegisteredSignalInfo[array_lengthof(IntSigs) + array_lengthof(KillSigs)];
  91. static void RegisterHandler(int Signal) {
  92. assert(NumRegisteredSignals < array_lengthof(RegisteredSignalInfo) &&
  93. "Out of space for signal handlers!");
  94. struct sigaction NewHandler;
  95. NewHandler.sa_handler = SignalHandler;
  96. NewHandler.sa_flags = SA_NODEFER | SA_RESETHAND | SA_ONSTACK;
  97. sigemptyset(&NewHandler.sa_mask);
  98. // Install the new handler, save the old one in RegisteredSignalInfo.
  99. sigaction(Signal, &NewHandler,
  100. &RegisteredSignalInfo[NumRegisteredSignals].SA);
  101. RegisteredSignalInfo[NumRegisteredSignals].SigNo = Signal;
  102. ++NumRegisteredSignals;
  103. }
  104. #if defined(HAVE_SIGALTSTACK)
  105. // Hold onto both the old and new alternate signal stack so that it's not
  106. // reported as a leak. We don't make any attempt to remove our alt signal
  107. // stack if we remove our signal handlers; that can't be done reliably if
  108. // someone else is also trying to do the same thing.
  109. static stack_t OldAltStack;
  110. static void* NewAltStackPointer;
  111. static void CreateSigAltStack() {
  112. const size_t AltStackSize = MINSIGSTKSZ + 64 * 1024;
  113. // If we're executing on the alternate stack, or we already have an alternate
  114. // signal stack that we're happy with, there's nothing for us to do. Don't
  115. // reduce the size, some other part of the process might need a larger stack
  116. // than we do.
  117. if (sigaltstack(nullptr, &OldAltStack) != 0 ||
  118. OldAltStack.ss_flags & SS_ONSTACK ||
  119. (OldAltStack.ss_sp && OldAltStack.ss_size >= AltStackSize))
  120. return;
  121. stack_t AltStack = {};
  122. AltStack.ss_sp = reinterpret_cast<char *>(malloc(AltStackSize));
  123. NewAltStackPointer = AltStack.ss_sp; // Save to avoid reporting a leak.
  124. AltStack.ss_size = AltStackSize;
  125. if (sigaltstack(&AltStack, &OldAltStack) != 0)
  126. free(AltStack.ss_sp);
  127. }
  128. #else
  129. static void CreateSigAltStack() {}
  130. #endif
  131. static void RegisterHandlers() {
  132. sys::SmartScopedLock<true> Guard(*SignalsMutex);
  133. // If the handlers are already registered, we're done.
  134. if (NumRegisteredSignals != 0) return;
  135. // Create an alternate stack for signal handling. This is necessary for us to
  136. // be able to reliably handle signals due to stack overflow.
  137. CreateSigAltStack();
  138. for (auto S : IntSigs) RegisterHandler(S);
  139. for (auto S : KillSigs) RegisterHandler(S);
  140. }
  141. static void UnregisterHandlers() {
  142. // Restore all of the signal handlers to how they were before we showed up.
  143. for (unsigned i = 0, e = NumRegisteredSignals; i != e; ++i)
  144. sigaction(RegisteredSignalInfo[i].SigNo,
  145. &RegisteredSignalInfo[i].SA, nullptr);
  146. NumRegisteredSignals = 0;
  147. }
  148. /// RemoveFilesToRemove - Process the FilesToRemove list. This function
  149. /// should be called with the SignalsMutex lock held.
  150. /// NB: This must be an async signal safe function. It cannot allocate or free
  151. /// memory, even in debug builds.
  152. static void RemoveFilesToRemove() {
  153. // Avoid constructing ManagedStatic in the signal handler.
  154. // If FilesToRemove is not constructed, there are no files to remove.
  155. if (!FilesToRemove.isConstructed())
  156. return;
  157. // We avoid iterators in case of debug iterators that allocate or release
  158. // memory.
  159. std::vector<std::string>& FilesToRemoveRef = *FilesToRemove;
  160. for (unsigned i = 0, e = FilesToRemoveRef.size(); i != e; ++i) {
  161. const char *path = FilesToRemoveRef[i].c_str();
  162. // Get the status so we can determine if it's a file or directory. If we
  163. // can't stat the file, ignore it.
  164. struct stat buf;
  165. if (stat(path, &buf) != 0)
  166. continue;
  167. // If this is not a regular file, ignore it. We want to prevent removal of
  168. // special files like /dev/null, even if the compiler is being run with the
  169. // super-user permissions.
  170. if (!S_ISREG(buf.st_mode))
  171. continue;
  172. // Otherwise, remove the file. We ignore any errors here as there is nothing
  173. // else we can do.
  174. unlink(path);
  175. }
  176. }
  177. // SignalHandler - The signal handler that runs.
  178. static RETSIGTYPE SignalHandler(int Sig) {
  179. // Restore the signal behavior to default, so that the program actually
  180. // crashes when we return and the signal reissues. This also ensures that if
  181. // we crash in our signal handler that the program will terminate immediately
  182. // instead of recursing in the signal handler.
  183. UnregisterHandlers();
  184. // Unmask all potentially blocked kill signals.
  185. sigset_t SigMask;
  186. sigfillset(&SigMask);
  187. sigprocmask(SIG_UNBLOCK, &SigMask, nullptr);
  188. {
  189. unique_lock<sys::SmartMutex<true>> Guard(*SignalsMutex);
  190. RemoveFilesToRemove();
  191. if (std::find(std::begin(IntSigs), std::end(IntSigs), Sig)
  192. != std::end(IntSigs)) {
  193. if (InterruptFunction) {
  194. void (*IF)() = InterruptFunction;
  195. Guard.unlock();
  196. InterruptFunction = nullptr;
  197. IF(); // run the interrupt function.
  198. return;
  199. }
  200. Guard.unlock();
  201. raise(Sig); // Execute the default handler.
  202. return;
  203. }
  204. }
  205. // Otherwise if it is a fault (like SEGV) run any handler.
  206. llvm::sys::RunSignalHandlers();
  207. #ifdef __s390__
  208. // On S/390, certain signals are delivered with PSW Address pointing to
  209. // *after* the faulting instruction. Simply returning from the signal
  210. // handler would continue execution after that point, instead of
  211. // re-raising the signal. Raise the signal manually in those cases.
  212. if (Sig == SIGILL || Sig == SIGFPE || Sig == SIGTRAP)
  213. raise(Sig);
  214. #endif
  215. }
  216. void llvm::sys::RunInterruptHandlers() {
  217. sys::SmartScopedLock<true> Guard(*SignalsMutex);
  218. RemoveFilesToRemove();
  219. }
  220. void llvm::sys::SetInterruptFunction(void (*IF)()) {
  221. {
  222. sys::SmartScopedLock<true> Guard(*SignalsMutex);
  223. InterruptFunction = IF;
  224. }
  225. RegisterHandlers();
  226. }
  227. // RemoveFileOnSignal - The public API
  228. bool llvm::sys::RemoveFileOnSignal(StringRef Filename,
  229. std::string* ErrMsg) {
  230. {
  231. sys::SmartScopedLock<true> Guard(*SignalsMutex);
  232. FilesToRemove->push_back(Filename);
  233. }
  234. RegisterHandlers();
  235. return false;
  236. }
  237. // DontRemoveFileOnSignal - The public API
  238. void llvm::sys::DontRemoveFileOnSignal(StringRef Filename) {
  239. sys::SmartScopedLock<true> Guard(*SignalsMutex);
  240. std::vector<std::string>::reverse_iterator RI =
  241. find(reverse(*FilesToRemove), Filename);
  242. std::vector<std::string>::iterator I = FilesToRemove->end();
  243. if (RI != FilesToRemove->rend())
  244. I = FilesToRemove->erase(RI.base()-1);
  245. }
  246. /// AddSignalHandler - Add a function to be called when a signal is delivered
  247. /// to the process. The handler can have a cookie passed to it to identify
  248. /// what instance of the handler it is.
  249. void llvm::sys::AddSignalHandler(void (*FnPtr)(void *), void *Cookie) {
  250. CallBacksToRun->push_back(std::make_pair(FnPtr, Cookie));
  251. RegisterHandlers();
  252. }
  253. #if defined(HAVE_BACKTRACE) && ENABLE_BACKTRACES && HAVE_LINK_H && \
  254. (defined(__linux__) || defined(__FreeBSD__) || \
  255. defined(__FreeBSD_kernel__) || defined(__NetBSD__))
  256. struct DlIteratePhdrData {
  257. void **StackTrace;
  258. int depth;
  259. bool first;
  260. const char **modules;
  261. intptr_t *offsets;
  262. const char *main_exec_name;
  263. };
  264. static int dl_iterate_phdr_cb(dl_phdr_info *info, size_t size, void *arg) {
  265. DlIteratePhdrData *data = (DlIteratePhdrData*)arg;
  266. const char *name = data->first ? data->main_exec_name : info->dlpi_name;
  267. data->first = false;
  268. for (int i = 0; i < info->dlpi_phnum; i++) {
  269. const auto *phdr = &info->dlpi_phdr[i];
  270. if (phdr->p_type != PT_LOAD)
  271. continue;
  272. intptr_t beg = info->dlpi_addr + phdr->p_vaddr;
  273. intptr_t end = beg + phdr->p_memsz;
  274. for (int j = 0; j < data->depth; j++) {
  275. if (data->modules[j])
  276. continue;
  277. intptr_t addr = (intptr_t)data->StackTrace[j];
  278. if (beg <= addr && addr < end) {
  279. data->modules[j] = name;
  280. data->offsets[j] = addr - info->dlpi_addr;
  281. }
  282. }
  283. }
  284. return 0;
  285. }
  286. /// If this is an ELF platform, we can find all loaded modules and their virtual
  287. /// addresses with dl_iterate_phdr.
  288. static bool findModulesAndOffsets(void **StackTrace, int Depth,
  289. const char **Modules, intptr_t *Offsets,
  290. const char *MainExecutableName,
  291. StringSaver &StrPool) {
  292. DlIteratePhdrData data = {StackTrace, Depth, true,
  293. Modules, Offsets, MainExecutableName};
  294. dl_iterate_phdr(dl_iterate_phdr_cb, &data);
  295. return true;
  296. }
  297. #else
  298. /// This platform does not have dl_iterate_phdr, so we do not yet know how to
  299. /// find all loaded DSOs.
  300. static bool findModulesAndOffsets(void **StackTrace, int Depth,
  301. const char **Modules, intptr_t *Offsets,
  302. const char *MainExecutableName,
  303. StringSaver &StrPool) {
  304. return false;
  305. }
  306. #endif // defined(HAVE_BACKTRACE) && ENABLE_BACKTRACES && ...
  307. #if ENABLE_BACKTRACES && defined(HAVE__UNWIND_BACKTRACE)
  308. static int unwindBacktrace(void **StackTrace, int MaxEntries) {
  309. if (MaxEntries < 0)
  310. return 0;
  311. // Skip the first frame ('unwindBacktrace' itself).
  312. int Entries = -1;
  313. auto HandleFrame = [&](_Unwind_Context *Context) -> _Unwind_Reason_Code {
  314. // Apparently we need to detect reaching the end of the stack ourselves.
  315. void *IP = (void *)_Unwind_GetIP(Context);
  316. if (!IP)
  317. return _URC_END_OF_STACK;
  318. assert(Entries < MaxEntries && "recursively called after END_OF_STACK?");
  319. if (Entries >= 0)
  320. StackTrace[Entries] = IP;
  321. if (++Entries == MaxEntries)
  322. return _URC_END_OF_STACK;
  323. return _URC_NO_REASON;
  324. };
  325. _Unwind_Backtrace(
  326. [](_Unwind_Context *Context, void *Handler) {
  327. return (*static_cast<decltype(HandleFrame) *>(Handler))(Context);
  328. },
  329. static_cast<void *>(&HandleFrame));
  330. return std::max(Entries, 0);
  331. }
  332. #endif
  333. // PrintStackTrace - In the case of a program crash or fault, print out a stack
  334. // trace so that the user has an indication of why and where we died.
  335. //
  336. // On glibc systems we have the 'backtrace' function, which works nicely, but
  337. // doesn't demangle symbols.
  338. void llvm::sys::PrintStackTrace(raw_ostream &OS) {
  339. #if ENABLE_BACKTRACES
  340. static void *StackTrace[256];
  341. int depth = 0;
  342. #if defined(HAVE_BACKTRACE)
  343. // Use backtrace() to output a backtrace on Linux systems with glibc.
  344. if (!depth)
  345. depth = backtrace(StackTrace, static_cast<int>(array_lengthof(StackTrace)));
  346. #endif
  347. #if defined(HAVE__UNWIND_BACKTRACE)
  348. // Try _Unwind_Backtrace() if backtrace() failed.
  349. if (!depth)
  350. depth = unwindBacktrace(StackTrace,
  351. static_cast<int>(array_lengthof(StackTrace)));
  352. #endif
  353. if (!depth)
  354. return;
  355. if (printSymbolizedStackTrace(Argv0, StackTrace, depth, OS))
  356. return;
  357. #if HAVE_DLFCN_H && HAVE_DLADDR
  358. int width = 0;
  359. for (int i = 0; i < depth; ++i) {
  360. Dl_info dlinfo;
  361. dladdr(StackTrace[i], &dlinfo);
  362. const char* name = strrchr(dlinfo.dli_fname, '/');
  363. int nwidth;
  364. if (!name) nwidth = strlen(dlinfo.dli_fname);
  365. else nwidth = strlen(name) - 1;
  366. if (nwidth > width) width = nwidth;
  367. }
  368. for (int i = 0; i < depth; ++i) {
  369. Dl_info dlinfo;
  370. dladdr(StackTrace[i], &dlinfo);
  371. OS << format("%-2d", i);
  372. const char* name = strrchr(dlinfo.dli_fname, '/');
  373. if (!name) OS << format(" %-*s", width, dlinfo.dli_fname);
  374. else OS << format(" %-*s", width, name+1);
  375. OS << format(" %#0*lx", (int)(sizeof(void*) * 2) + 2,
  376. (unsigned long)StackTrace[i]);
  377. if (dlinfo.dli_sname != nullptr) {
  378. OS << ' ';
  379. int res;
  380. char* d = itaniumDemangle(dlinfo.dli_sname, nullptr, nullptr, &res);
  381. if (!d) OS << dlinfo.dli_sname;
  382. else OS << d;
  383. free(d);
  384. // FIXME: When we move to C++11, use %t length modifier. It's not in
  385. // C++03 and causes gcc to issue warnings. Losing the upper 32 bits of
  386. // the stack offset for a stack dump isn't likely to cause any problems.
  387. OS << format(" + %u",(unsigned)((char*)StackTrace[i]-
  388. (char*)dlinfo.dli_saddr));
  389. }
  390. OS << '\n';
  391. }
  392. #elif defined(HAVE_BACKTRACE)
  393. backtrace_symbols_fd(StackTrace, depth, STDERR_FILENO);
  394. #endif
  395. #endif
  396. }
  397. static void PrintStackTraceSignalHandler(void *) {
  398. sys::PrintStackTrace(llvm::errs());
  399. }
  400. void llvm::sys::DisableSystemDialogsOnCrash() {}
  401. /// PrintStackTraceOnErrorSignal - When an error signal (such as SIGABRT or
  402. /// SIGSEGV) is delivered to the process, print a stack trace and then exit.
  403. void llvm::sys::PrintStackTraceOnErrorSignal(StringRef Argv0,
  404. bool DisableCrashReporting) {
  405. ::Argv0 = Argv0;
  406. AddSignalHandler(PrintStackTraceSignalHandler, nullptr);
  407. #if defined(__APPLE__) && ENABLE_CRASH_OVERRIDES
  408. // Environment variable to disable any kind of crash dialog.
  409. if (DisableCrashReporting || getenv("LLVM_DISABLE_CRASH_REPORT")) {
  410. mach_port_t self = mach_task_self();
  411. exception_mask_t mask = EXC_MASK_CRASH;
  412. kern_return_t ret = task_set_exception_ports(self,
  413. mask,
  414. MACH_PORT_NULL,
  415. EXCEPTION_STATE_IDENTITY | MACH_EXCEPTION_CODES,
  416. THREAD_STATE_NONE);
  417. (void)ret;
  418. }
  419. #endif
  420. }