Signals.inc 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558
  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/Support/Format.h"
  17. #include "llvm/Support/FileSystem.h"
  18. #include "llvm/Support/FileUtilities.h"
  19. #include "llvm/Support/ManagedStatic.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. #include <vector>
  28. #if HAVE_EXECINFO_H
  29. # include <execinfo.h> // For backtrace().
  30. #endif
  31. #if HAVE_SIGNAL_H
  32. #include <signal.h>
  33. #endif
  34. #if HAVE_SYS_STAT_H
  35. #include <sys/stat.h>
  36. #endif
  37. #if HAVE_CXXABI_H
  38. #include <cxxabi.h>
  39. #endif
  40. #if HAVE_DLFCN_H
  41. #include <dlfcn.h>
  42. #endif
  43. #if HAVE_MACH_MACH_H
  44. #include <mach/mach.h>
  45. #endif
  46. #if HAVE_LINK_H
  47. #include <link.h>
  48. #endif
  49. using namespace llvm;
  50. static RETSIGTYPE SignalHandler(int Sig); // defined below.
  51. static ManagedStatic<SmartMutex<true> > SignalsMutex;
  52. /// InterruptFunction - The function to call if ctrl-c is pressed.
  53. static void (*InterruptFunction)() = nullptr;
  54. static ManagedStatic<std::vector<std::string>> FilesToRemove;
  55. static ManagedStatic<std::vector<std::pair<void (*)(void *), void *>>>
  56. CallBacksToRun;
  57. // IntSigs - Signals that represent requested termination. There's no bug
  58. // or failure, or if there is, it's not our direct responsibility. For whatever
  59. // reason, our continued execution is no longer desirable.
  60. static const int IntSigs[] = {
  61. SIGHUP, SIGINT, SIGPIPE, SIGTERM, SIGUSR1, SIGUSR2
  62. };
  63. // KillSigs - Signals that represent that we have a bug, and our prompt
  64. // termination has been ordered.
  65. static const int KillSigs[] = {
  66. SIGILL, SIGTRAP, SIGABRT, SIGFPE, SIGBUS, SIGSEGV, SIGQUIT
  67. #ifdef SIGSYS
  68. , SIGSYS
  69. #endif
  70. #ifdef SIGXCPU
  71. , SIGXCPU
  72. #endif
  73. #ifdef SIGXFSZ
  74. , SIGXFSZ
  75. #endif
  76. #ifdef SIGEMT
  77. , SIGEMT
  78. #endif
  79. };
  80. static unsigned NumRegisteredSignals = 0;
  81. static struct {
  82. struct sigaction SA;
  83. int SigNo;
  84. } RegisteredSignalInfo[(sizeof(IntSigs)+sizeof(KillSigs))/sizeof(KillSigs[0])];
  85. static void RegisterHandler(int Signal) {
  86. assert(NumRegisteredSignals <
  87. sizeof(RegisteredSignalInfo)/sizeof(RegisteredSignalInfo[0]) &&
  88. "Out of space for signal handlers!");
  89. struct sigaction NewHandler;
  90. NewHandler.sa_handler = SignalHandler;
  91. NewHandler.sa_flags = SA_NODEFER|SA_RESETHAND;
  92. sigemptyset(&NewHandler.sa_mask);
  93. // Install the new handler, save the old one in RegisteredSignalInfo.
  94. sigaction(Signal, &NewHandler,
  95. &RegisteredSignalInfo[NumRegisteredSignals].SA);
  96. RegisteredSignalInfo[NumRegisteredSignals].SigNo = Signal;
  97. ++NumRegisteredSignals;
  98. }
  99. static void RegisterHandlers() {
  100. // We need to dereference the signals mutex during handler registration so
  101. // that we force its construction. This is to prevent the first use being
  102. // during handling an actual signal because you can't safely call new in a
  103. // signal handler.
  104. *SignalsMutex;
  105. // If the handlers are already registered, we're done.
  106. if (NumRegisteredSignals != 0) return;
  107. for (auto S : IntSigs) RegisterHandler(S);
  108. for (auto S : KillSigs) RegisterHandler(S);
  109. }
  110. static void UnregisterHandlers() {
  111. // Restore all of the signal handlers to how they were before we showed up.
  112. for (unsigned i = 0, e = NumRegisteredSignals; i != e; ++i)
  113. sigaction(RegisteredSignalInfo[i].SigNo,
  114. &RegisteredSignalInfo[i].SA, nullptr);
  115. NumRegisteredSignals = 0;
  116. }
  117. /// RemoveFilesToRemove - Process the FilesToRemove list. This function
  118. /// should be called with the SignalsMutex lock held.
  119. /// NB: This must be an async signal safe function. It cannot allocate or free
  120. /// memory, even in debug builds.
  121. static void RemoveFilesToRemove() {
  122. // Avoid constructing ManagedStatic in the signal handler.
  123. // If FilesToRemove is not constructed, there are no files to remove.
  124. if (!FilesToRemove.isConstructed())
  125. return;
  126. // We avoid iterators in case of debug iterators that allocate or release
  127. // memory.
  128. std::vector<std::string>& FilesToRemoveRef = *FilesToRemove;
  129. for (unsigned i = 0, e = FilesToRemoveRef.size(); i != e; ++i) {
  130. // We rely on a std::string implementation for which repeated calls to
  131. // 'c_str()' don't allocate memory. We pre-call 'c_str()' on all of these
  132. // strings to try to ensure this is safe.
  133. const char *path = FilesToRemoveRef[i].c_str();
  134. // Get the status so we can determine if it's a file or directory. If we
  135. // can't stat the file, ignore it.
  136. struct stat buf;
  137. if (stat(path, &buf) != 0)
  138. continue;
  139. // If this is not a regular file, ignore it. We want to prevent removal of
  140. // special files like /dev/null, even if the compiler is being run with the
  141. // super-user permissions.
  142. if (!S_ISREG(buf.st_mode))
  143. continue;
  144. // Otherwise, remove the file. We ignore any errors here as there is nothing
  145. // else we can do.
  146. unlink(path);
  147. }
  148. }
  149. // SignalHandler - The signal handler that runs.
  150. static RETSIGTYPE SignalHandler(int Sig) {
  151. // Restore the signal behavior to default, so that the program actually
  152. // crashes when we return and the signal reissues. This also ensures that if
  153. // we crash in our signal handler that the program will terminate immediately
  154. // instead of recursing in the signal handler.
  155. UnregisterHandlers();
  156. // Unmask all potentially blocked kill signals.
  157. sigset_t SigMask;
  158. sigfillset(&SigMask);
  159. sigprocmask(SIG_UNBLOCK, &SigMask, nullptr);
  160. {
  161. unique_lock<SmartMutex<true>> Guard(*SignalsMutex);
  162. RemoveFilesToRemove();
  163. if (std::find(std::begin(IntSigs), std::end(IntSigs), Sig)
  164. != std::end(IntSigs)) {
  165. if (InterruptFunction) {
  166. void (*IF)() = InterruptFunction;
  167. Guard.unlock();
  168. InterruptFunction = nullptr;
  169. IF(); // run the interrupt function.
  170. return;
  171. }
  172. Guard.unlock();
  173. raise(Sig); // Execute the default handler.
  174. return;
  175. }
  176. }
  177. // Otherwise if it is a fault (like SEGV) run any handler.
  178. if (CallBacksToRun.isConstructed()) {
  179. auto &CallBacksToRunRef = *CallBacksToRun;
  180. for (unsigned i = 0, e = CallBacksToRun->size(); i != e; ++i)
  181. CallBacksToRunRef[i].first(CallBacksToRunRef[i].second);
  182. }
  183. #ifdef __s390__
  184. // On S/390, certain signals are delivered with PSW Address pointing to
  185. // *after* the faulting instruction. Simply returning from the signal
  186. // handler would continue execution after that point, instead of
  187. // re-raising the signal. Raise the signal manually in those cases.
  188. if (Sig == SIGILL || Sig == SIGFPE || Sig == SIGTRAP)
  189. raise(Sig);
  190. #endif
  191. }
  192. void llvm::sys::RunInterruptHandlers() {
  193. sys::SmartScopedLock<true> Guard(*SignalsMutex);
  194. RemoveFilesToRemove();
  195. }
  196. void llvm::sys::SetInterruptFunction(void (*IF)()) {
  197. {
  198. sys::SmartScopedLock<true> Guard(*SignalsMutex);
  199. InterruptFunction = IF;
  200. }
  201. RegisterHandlers();
  202. }
  203. // RemoveFileOnSignal - The public API
  204. bool llvm::sys::RemoveFileOnSignal(StringRef Filename,
  205. std::string* ErrMsg) {
  206. {
  207. sys::SmartScopedLock<true> Guard(*SignalsMutex);
  208. std::vector<std::string>& FilesToRemoveRef = *FilesToRemove;
  209. std::string *OldPtr =
  210. FilesToRemoveRef.empty() ? nullptr : &FilesToRemoveRef[0];
  211. FilesToRemoveRef.push_back(Filename);
  212. // We want to call 'c_str()' on every std::string in this vector so that if
  213. // the underlying implementation requires a re-allocation, it happens here
  214. // rather than inside of the signal handler. If we see the vector grow, we
  215. // have to call it on every entry. If it remains in place, we only need to
  216. // call it on the latest one.
  217. if (OldPtr == &FilesToRemoveRef[0])
  218. FilesToRemoveRef.back().c_str();
  219. else
  220. for (unsigned i = 0, e = FilesToRemoveRef.size(); i != e; ++i)
  221. FilesToRemoveRef[i].c_str();
  222. }
  223. RegisterHandlers();
  224. return false;
  225. }
  226. // DontRemoveFileOnSignal - The public API
  227. void llvm::sys::DontRemoveFileOnSignal(StringRef Filename) {
  228. sys::SmartScopedLock<true> Guard(*SignalsMutex);
  229. std::vector<std::string>::reverse_iterator RI =
  230. std::find(FilesToRemove->rbegin(), FilesToRemove->rend(), Filename);
  231. std::vector<std::string>::iterator I = FilesToRemove->end();
  232. if (RI != FilesToRemove->rend())
  233. I = FilesToRemove->erase(RI.base()-1);
  234. // We need to call c_str() on every element which would have been moved by
  235. // the erase. These elements, in a C++98 implementation where c_str()
  236. // requires a reallocation on the first call may have had the call to c_str()
  237. // made on insertion become invalid by being copied down an element.
  238. for (std::vector<std::string>::iterator E = FilesToRemove->end(); I != E; ++I)
  239. I->c_str();
  240. }
  241. /// AddSignalHandler - Add a function to be called when a signal is delivered
  242. /// to the process. The handler can have a cookie passed to it to identify
  243. /// what instance of the handler it is.
  244. void llvm::sys::AddSignalHandler(void (*FnPtr)(void *), void *Cookie) {
  245. CallBacksToRun->push_back(std::make_pair(FnPtr, Cookie));
  246. RegisterHandlers();
  247. }
  248. #if defined(HAVE_BACKTRACE) && defined(ENABLE_BACKTRACES)
  249. #if HAVE_LINK_H && (defined(__linux__) || defined(__FreeBSD__) || \
  250. defined(__FreeBSD_kernel__) || defined(__NetBSD__))
  251. struct DlIteratePhdrData {
  252. void **StackTrace;
  253. int depth;
  254. bool first;
  255. const char **modules;
  256. intptr_t *offsets;
  257. const char *main_exec_name;
  258. };
  259. static int dl_iterate_phdr_cb(dl_phdr_info *info, size_t size, void *arg) {
  260. DlIteratePhdrData *data = (DlIteratePhdrData*)arg;
  261. const char *name = data->first ? data->main_exec_name : info->dlpi_name;
  262. data->first = false;
  263. for (int i = 0; i < info->dlpi_phnum; i++) {
  264. const auto *phdr = &info->dlpi_phdr[i];
  265. if (phdr->p_type != PT_LOAD)
  266. continue;
  267. intptr_t beg = info->dlpi_addr + phdr->p_vaddr;
  268. intptr_t end = beg + phdr->p_memsz;
  269. for (int j = 0; j < data->depth; j++) {
  270. if (data->modules[j])
  271. continue;
  272. intptr_t addr = (intptr_t)data->StackTrace[j];
  273. if (beg <= addr && addr < end) {
  274. data->modules[j] = name;
  275. data->offsets[j] = addr - info->dlpi_addr;
  276. }
  277. }
  278. }
  279. return 0;
  280. }
  281. static bool findModulesAndOffsets(void **StackTrace, int Depth,
  282. const char **Modules, intptr_t *Offsets,
  283. const char *MainExecutableName) {
  284. DlIteratePhdrData data = {StackTrace, Depth, true,
  285. Modules, Offsets, MainExecutableName};
  286. dl_iterate_phdr(dl_iterate_phdr_cb, &data);
  287. return true;
  288. }
  289. #else
  290. static bool findModulesAndOffsets(void **StackTrace, int Depth,
  291. const char **Modules, intptr_t *Offsets,
  292. const char *MainExecutableName) {
  293. return false;
  294. }
  295. #endif
  296. static bool printSymbolizedStackTrace(void **StackTrace, int Depth,
  297. llvm::raw_ostream &OS) {
  298. // FIXME: Subtract necessary number from StackTrace entries to turn return addresses
  299. // into actual instruction addresses.
  300. // Use llvm-symbolizer tool to symbolize the stack traces.
  301. ErrorOr<std::string> LLVMSymbolizerPathOrErr =
  302. sys::findProgramByName("llvm-symbolizer");
  303. if (!LLVMSymbolizerPathOrErr)
  304. return false;
  305. const std::string &LLVMSymbolizerPath = *LLVMSymbolizerPathOrErr;
  306. // We don't know argv0 or the address of main() at this point, but try
  307. // to guess it anyway (it's possible on some platforms).
  308. std::string MainExecutableName = sys::fs::getMainExecutable(nullptr, nullptr);
  309. if (MainExecutableName.empty() ||
  310. MainExecutableName.find("llvm-symbolizer") != std::string::npos)
  311. return false;
  312. std::vector<const char *> Modules(Depth, nullptr);
  313. std::vector<intptr_t> Offsets(Depth, 0);
  314. if (!findModulesAndOffsets(StackTrace, Depth, Modules.data(), Offsets.data(),
  315. MainExecutableName.c_str()))
  316. return false;
  317. int InputFD;
  318. SmallString<32> InputFile, OutputFile;
  319. sys::fs::createTemporaryFile("symbolizer-input", "", InputFD, InputFile);
  320. sys::fs::createTemporaryFile("symbolizer-output", "", OutputFile);
  321. FileRemover InputRemover(InputFile.c_str());
  322. FileRemover OutputRemover(OutputFile.c_str());
  323. {
  324. raw_fd_ostream Input(InputFD, true);
  325. for (int i = 0; i < Depth; i++) {
  326. if (Modules[i])
  327. Input << Modules[i] << " " << (void*)Offsets[i] << "\n";
  328. }
  329. }
  330. StringRef InputFileStr(InputFile);
  331. StringRef OutputFileStr(OutputFile);
  332. StringRef StderrFileStr;
  333. const StringRef *Redirects[] = {&InputFileStr, &OutputFileStr,
  334. &StderrFileStr};
  335. const char *Args[] = {"llvm-symbolizer", "--functions=linkage", "--inlining",
  336. "--demangle", nullptr};
  337. int RunResult =
  338. sys::ExecuteAndWait(LLVMSymbolizerPath, Args, nullptr, Redirects);
  339. if (RunResult != 0)
  340. return false;
  341. auto OutputBuf = MemoryBuffer::getFile(OutputFile.c_str());
  342. if (!OutputBuf)
  343. return false;
  344. StringRef Output = OutputBuf.get()->getBuffer();
  345. SmallVector<StringRef, 32> Lines;
  346. Output.split(Lines, "\n");
  347. auto CurLine = Lines.begin();
  348. int frame_no = 0;
  349. for (int i = 0; i < Depth; i++) {
  350. if (!Modules[i]) {
  351. OS << format("#%d %p\n", frame_no++, StackTrace[i]);
  352. continue;
  353. }
  354. // Read pairs of lines (function name and file/line info) until we
  355. // encounter empty line.
  356. for (;;) {
  357. if (CurLine == Lines.end())
  358. return false;
  359. StringRef FunctionName = *CurLine++;
  360. if (FunctionName.empty())
  361. break;
  362. OS << format("#%d %p ", frame_no++, StackTrace[i]);
  363. if (!FunctionName.startswith("??"))
  364. OS << format("%s ", FunctionName.str().c_str());
  365. if (CurLine == Lines.end())
  366. return false;
  367. StringRef FileLineInfo = *CurLine++;
  368. if (!FileLineInfo.startswith("??"))
  369. OS << format("%s", FileLineInfo.str().c_str());
  370. else
  371. OS << format("(%s+%p)", Modules[i], (void *)Offsets[i]);
  372. OS << "\n";
  373. }
  374. }
  375. return true;
  376. }
  377. #endif // defined(HAVE_BACKTRACE) && defined(ENABLE_BACKTRACES)
  378. // PrintStackTrace - In the case of a program crash or fault, print out a stack
  379. // trace so that the user has an indication of why and where we died.
  380. //
  381. // On glibc systems we have the 'backtrace' function, which works nicely, but
  382. // doesn't demangle symbols.
  383. void llvm::sys::PrintStackTrace(raw_ostream &OS) {
  384. #if defined(HAVE_BACKTRACE) && defined(ENABLE_BACKTRACES)
  385. static void* StackTrace[256];
  386. // Use backtrace() to output a backtrace on Linux systems with glibc.
  387. int depth = backtrace(StackTrace,
  388. static_cast<int>(array_lengthof(StackTrace)));
  389. if (printSymbolizedStackTrace(StackTrace, depth, OS))
  390. return;
  391. #if HAVE_DLFCN_H && __GNUG__
  392. int width = 0;
  393. for (int i = 0; i < depth; ++i) {
  394. Dl_info dlinfo;
  395. dladdr(StackTrace[i], &dlinfo);
  396. const char* name = strrchr(dlinfo.dli_fname, '/');
  397. int nwidth;
  398. if (!name) nwidth = strlen(dlinfo.dli_fname);
  399. else nwidth = strlen(name) - 1;
  400. if (nwidth > width) width = nwidth;
  401. }
  402. for (int i = 0; i < depth; ++i) {
  403. Dl_info dlinfo;
  404. dladdr(StackTrace[i], &dlinfo);
  405. OS << format("%-2d", i);
  406. const char* name = strrchr(dlinfo.dli_fname, '/');
  407. if (!name) OS << format(" %-*s", width, dlinfo.dli_fname);
  408. else OS << format(" %-*s", width, name+1);
  409. OS << format(" %#0*lx", (int)(sizeof(void*) * 2) + 2,
  410. (unsigned long)StackTrace[i]);
  411. if (dlinfo.dli_sname != nullptr) {
  412. OS << ' ';
  413. # if HAVE_CXXABI_H
  414. int res;
  415. char* d = abi::__cxa_demangle(dlinfo.dli_sname, nullptr, nullptr, &res);
  416. # else
  417. char* d = NULL;
  418. # endif
  419. if (!d) OS << dlinfo.dli_sname;
  420. else OS << d;
  421. free(d);
  422. // FIXME: When we move to C++11, use %t length modifier. It's not in
  423. // C++03 and causes gcc to issue warnings. Losing the upper 32 bits of
  424. // the stack offset for a stack dump isn't likely to cause any problems.
  425. OS << format(" + %u",(unsigned)((char*)StackTrace[i]-
  426. (char*)dlinfo.dli_saddr));
  427. }
  428. OS << '\n';
  429. }
  430. #else
  431. backtrace_symbols_fd(StackTrace, depth, STDERR_FILENO);
  432. #endif
  433. #endif
  434. }
  435. static void PrintStackTraceSignalHandler(void *) {
  436. PrintStackTrace(llvm::errs());
  437. }
  438. void llvm::sys::DisableSystemDialogsOnCrash() {}
  439. /// PrintStackTraceOnErrorSignal - When an error signal (such as SIGABRT or
  440. /// SIGSEGV) is delivered to the process, print a stack trace and then exit.
  441. void llvm::sys::PrintStackTraceOnErrorSignal(bool DisableCrashReporting) {
  442. AddSignalHandler(PrintStackTraceSignalHandler, nullptr);
  443. #if defined(__APPLE__) && defined(ENABLE_CRASH_OVERRIDES)
  444. // Environment variable to disable any kind of crash dialog.
  445. if (DisableCrashReporting || getenv("LLVM_DISABLE_CRASH_REPORT")) {
  446. mach_port_t self = mach_task_self();
  447. exception_mask_t mask = EXC_MASK_CRASH;
  448. kern_return_t ret = task_set_exception_ports(self,
  449. mask,
  450. MACH_PORT_NULL,
  451. EXCEPTION_STATE_IDENTITY | MACH_EXCEPTION_CODES,
  452. THREAD_STATE_NONE);
  453. (void)ret;
  454. }
  455. #endif
  456. }
  457. /***/
  458. // On Darwin, raise sends a signal to the main thread instead of the current
  459. // thread. This has the unfortunate effect that assert() and abort() will end up
  460. // bypassing our crash recovery attempts. We work around this for anything in
  461. // the same linkage unit by just defining our own versions of the assert handler
  462. // and abort.
  463. #if defined(__APPLE__) && defined(ENABLE_CRASH_OVERRIDES)
  464. #include <signal.h>
  465. #include <pthread.h>
  466. int raise(int sig) {
  467. return pthread_kill(pthread_self(), sig);
  468. }
  469. void __assert_rtn(const char *func,
  470. const char *file,
  471. int line,
  472. const char *expr) {
  473. if (func)
  474. fprintf(stderr, "Assertion failed: (%s), function %s, file %s, line %d.\n",
  475. expr, func, file, line);
  476. else
  477. fprintf(stderr, "Assertion failed: (%s), file %s, line %d.\n",
  478. expr, file, line);
  479. abort();
  480. }
  481. void abort() {
  482. raise(SIGABRT);
  483. usleep(1000);
  484. __builtin_trap();
  485. }
  486. #endif