Signals.inc 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642
  1. //===- Signals.cpp - Generic Unix Signals Implementation -----*- C++ -*-===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // This file defines some helpful functions for dealing with the possibility of
  10. // Unix signals occurring while your program is running.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. //
  14. // This file is extremely careful to only do signal-safe things while in a
  15. // signal handler. In particular, memory allocation and acquiring a mutex
  16. // while in a signal handler should never occur. ManagedStatic isn't usable from
  17. // a signal handler for 2 reasons:
  18. //
  19. // 1. Creating a new one allocates.
  20. // 2. The signal handler could fire while llvm_shutdown is being processed, in
  21. // which case the ManagedStatic is in an unknown state because it could
  22. // already have been destroyed, or be in the process of being destroyed.
  23. //
  24. // Modifying the behavior of the signal handlers (such as registering new ones)
  25. // can acquire a mutex, but all this guarantees is that the signal handler
  26. // behavior is only modified by one thread at a time. A signal handler can still
  27. // fire while this occurs!
  28. //
  29. // Adding work to a signal handler requires lock-freedom (and assume atomics are
  30. // always lock-free) because the signal handler could fire while new work is
  31. // being added.
  32. //
  33. //===----------------------------------------------------------------------===//
  34. #include "Unix.h"
  35. #include "llvm/ADT/STLExtras.h"
  36. #include "llvm/Config/config.h"
  37. #include "llvm/Demangle/Demangle.h"
  38. #include "llvm/Support/FileSystem.h"
  39. #include "llvm/Support/FileUtilities.h"
  40. #include "llvm/Support/Format.h"
  41. #include "llvm/Support/MemoryBuffer.h"
  42. #include "llvm/Support/Mutex.h"
  43. #include "llvm/Support/Program.h"
  44. #include "llvm/Support/SaveAndRestore.h"
  45. #include "llvm/Support/raw_ostream.h"
  46. #include <algorithm>
  47. #include <string>
  48. #include <sysexits.h>
  49. #ifdef HAVE_BACKTRACE
  50. # include BACKTRACE_HEADER // For backtrace().
  51. #endif
  52. #if HAVE_SIGNAL_H
  53. #include <signal.h>
  54. #endif
  55. #if HAVE_SYS_STAT_H
  56. #include <sys/stat.h>
  57. #endif
  58. #if HAVE_DLFCN_H
  59. #include <dlfcn.h>
  60. #endif
  61. #if HAVE_MACH_MACH_H
  62. #include <mach/mach.h>
  63. #endif
  64. #if HAVE_LINK_H
  65. #include <link.h>
  66. #endif
  67. #ifdef HAVE__UNWIND_BACKTRACE
  68. // FIXME: We should be able to use <unwind.h> for any target that has an
  69. // _Unwind_Backtrace function, but on FreeBSD the configure test passes
  70. // despite the function not existing, and on Android, <unwind.h> conflicts
  71. // with <link.h>.
  72. #ifdef __GLIBC__
  73. #include <unwind.h>
  74. #else
  75. #undef HAVE__UNWIND_BACKTRACE
  76. #endif
  77. #endif
  78. #ifdef __APPLE__
  79. #include <TargetConditionals.h>
  80. #endif
  81. using namespace llvm;
  82. static RETSIGTYPE SignalHandler(int Sig); // defined below.
  83. static RETSIGTYPE InfoSignalHandler(int Sig); // defined below.
  84. static void DefaultPipeSignalFunction() {
  85. exit(EX_IOERR);
  86. }
  87. using SignalHandlerFunctionType = void (*)();
  88. /// The function to call if ctrl-c is pressed.
  89. static std::atomic<SignalHandlerFunctionType> InterruptFunction =
  90. ATOMIC_VAR_INIT(nullptr);
  91. static std::atomic<SignalHandlerFunctionType> InfoSignalFunction =
  92. ATOMIC_VAR_INIT(nullptr);
  93. static std::atomic<SignalHandlerFunctionType> PipeSignalFunction =
  94. ATOMIC_VAR_INIT(DefaultPipeSignalFunction);
  95. namespace {
  96. /// Signal-safe removal of files.
  97. /// Inserting and erasing from the list isn't signal-safe, but removal of files
  98. /// themselves is signal-safe. Memory is freed when the head is freed, deletion
  99. /// is therefore not signal-safe either.
  100. class FileToRemoveList {
  101. std::atomic<char *> Filename = ATOMIC_VAR_INIT(nullptr);
  102. std::atomic<FileToRemoveList *> Next = ATOMIC_VAR_INIT(nullptr);
  103. FileToRemoveList() = default;
  104. // Not signal-safe.
  105. FileToRemoveList(const std::string &str) : Filename(strdup(str.c_str())) {}
  106. public:
  107. // Not signal-safe.
  108. ~FileToRemoveList() {
  109. if (FileToRemoveList *N = Next.exchange(nullptr))
  110. delete N;
  111. if (char *F = Filename.exchange(nullptr))
  112. free(F);
  113. }
  114. // Not signal-safe.
  115. static void insert(std::atomic<FileToRemoveList *> &Head,
  116. const std::string &Filename) {
  117. // Insert the new file at the end of the list.
  118. FileToRemoveList *NewHead = new FileToRemoveList(Filename);
  119. std::atomic<FileToRemoveList *> *InsertionPoint = &Head;
  120. FileToRemoveList *OldHead = nullptr;
  121. while (!InsertionPoint->compare_exchange_strong(OldHead, NewHead)) {
  122. InsertionPoint = &OldHead->Next;
  123. OldHead = nullptr;
  124. }
  125. }
  126. // Not signal-safe.
  127. static void erase(std::atomic<FileToRemoveList *> &Head,
  128. const std::string &Filename) {
  129. // Use a lock to avoid concurrent erase: the comparison would access
  130. // free'd memory.
  131. static ManagedStatic<sys::SmartMutex<true>> Lock;
  132. sys::SmartScopedLock<true> Writer(*Lock);
  133. for (FileToRemoveList *Current = Head.load(); Current;
  134. Current = Current->Next.load()) {
  135. if (char *OldFilename = Current->Filename.load()) {
  136. if (OldFilename != Filename)
  137. continue;
  138. // Leave an empty filename.
  139. OldFilename = Current->Filename.exchange(nullptr);
  140. // The filename might have become null between the time we
  141. // compared it and we exchanged it.
  142. if (OldFilename)
  143. free(OldFilename);
  144. }
  145. }
  146. }
  147. // Signal-safe.
  148. static void removeAllFiles(std::atomic<FileToRemoveList *> &Head) {
  149. // If cleanup were to occur while we're removing files we'd have a bad time.
  150. // Make sure we're OK by preventing cleanup from doing anything while we're
  151. // removing files. If cleanup races with us and we win we'll have a leak,
  152. // but we won't crash.
  153. FileToRemoveList *OldHead = Head.exchange(nullptr);
  154. for (FileToRemoveList *currentFile = OldHead; currentFile;
  155. currentFile = currentFile->Next.load()) {
  156. // If erasing was occuring while we're trying to remove files we'd look
  157. // at free'd data. Take away the path and put it back when done.
  158. if (char *path = currentFile->Filename.exchange(nullptr)) {
  159. // Get the status so we can determine if it's a file or directory. If we
  160. // can't stat the file, ignore it.
  161. struct stat buf;
  162. if (stat(path, &buf) != 0)
  163. continue;
  164. // If this is not a regular file, ignore it. We want to prevent removal
  165. // of special files like /dev/null, even if the compiler is being run
  166. // with the super-user permissions.
  167. if (!S_ISREG(buf.st_mode))
  168. continue;
  169. // Otherwise, remove the file. We ignore any errors here as there is
  170. // nothing else we can do.
  171. unlink(path);
  172. // We're done removing the file, erasing can safely proceed.
  173. currentFile->Filename.exchange(path);
  174. }
  175. }
  176. // We're done removing files, cleanup can safely proceed.
  177. Head.exchange(OldHead);
  178. }
  179. };
  180. static std::atomic<FileToRemoveList *> FilesToRemove = ATOMIC_VAR_INIT(nullptr);
  181. /// Clean up the list in a signal-friendly manner.
  182. /// Recall that signals can fire during llvm_shutdown. If this occurs we should
  183. /// either clean something up or nothing at all, but we shouldn't crash!
  184. struct FilesToRemoveCleanup {
  185. // Not signal-safe.
  186. ~FilesToRemoveCleanup() {
  187. FileToRemoveList *Head = FilesToRemove.exchange(nullptr);
  188. if (Head)
  189. delete Head;
  190. }
  191. };
  192. } // namespace
  193. static StringRef Argv0;
  194. /// Signals that represent requested termination. There's no bug or failure, or
  195. /// if there is, it's not our direct responsibility. For whatever reason, our
  196. /// continued execution is no longer desirable.
  197. static const int IntSigs[] = {
  198. #if !TARGET_OS_IPHONE
  199. SIGHUP, SIGINT, SIGPIPE, SIGTERM, SIGUSR2
  200. #else
  201. // leave SIGUSR2 alone when running on iPhone (we need it for Python)
  202. // This is not perfect, but signals and threads is a difficult combination.
  203. SIGHUP, SIGINT, SIGPIPE, SIGTERM
  204. #endif
  205. };
  206. /// Signals that represent that we have a bug, and our prompt termination has
  207. /// been ordered.
  208. static const int KillSigs[] = {
  209. SIGILL, SIGTRAP, SIGABRT, SIGFPE, SIGBUS, SIGSEGV, SIGQUIT
  210. #ifdef SIGSYS
  211. , SIGSYS
  212. #endif
  213. #ifdef SIGXCPU
  214. , SIGXCPU
  215. #endif
  216. #ifdef SIGXFSZ
  217. , SIGXFSZ
  218. #endif
  219. #ifdef SIGEMT
  220. , SIGEMT
  221. #endif
  222. };
  223. /// Signals that represent requests for status.
  224. static const int InfoSigs[] = {
  225. SIGUSR1
  226. #ifdef SIGINFO
  227. , SIGINFO
  228. #endif
  229. };
  230. static const size_t NumSigs =
  231. array_lengthof(IntSigs) + array_lengthof(KillSigs) +
  232. array_lengthof(InfoSigs);
  233. static std::atomic<unsigned> NumRegisteredSignals = ATOMIC_VAR_INIT(0);
  234. static struct {
  235. struct sigaction SA;
  236. int SigNo;
  237. } RegisteredSignalInfo[NumSigs];
  238. #if defined(HAVE_SIGALTSTACK)
  239. // Hold onto both the old and new alternate signal stack so that it's not
  240. // reported as a leak. We don't make any attempt to remove our alt signal
  241. // stack if we remove our signal handlers; that can't be done reliably if
  242. // someone else is also trying to do the same thing.
  243. static stack_t OldAltStack;
  244. static void* NewAltStackPointer;
  245. static void CreateSigAltStack() {
  246. const size_t AltStackSize = MINSIGSTKSZ + 64 * 1024;
  247. // If we're executing on the alternate stack, or we already have an alternate
  248. // signal stack that we're happy with, there's nothing for us to do. Don't
  249. // reduce the size, some other part of the process might need a larger stack
  250. // than we do.
  251. if (sigaltstack(nullptr, &OldAltStack) != 0 ||
  252. OldAltStack.ss_flags & SS_ONSTACK ||
  253. (OldAltStack.ss_sp && OldAltStack.ss_size >= AltStackSize))
  254. return;
  255. stack_t AltStack = {};
  256. AltStack.ss_sp = static_cast<char *>(safe_malloc(AltStackSize));
  257. NewAltStackPointer = AltStack.ss_sp; // Save to avoid reporting a leak.
  258. AltStack.ss_size = AltStackSize;
  259. if (sigaltstack(&AltStack, &OldAltStack) != 0)
  260. free(AltStack.ss_sp);
  261. }
  262. #else
  263. static void CreateSigAltStack() {}
  264. #endif
  265. static void RegisterHandlers() { // Not signal-safe.
  266. // The mutex prevents other threads from registering handlers while we're
  267. // doing it. We also have to protect the handlers and their count because
  268. // a signal handler could fire while we're registeting handlers.
  269. static ManagedStatic<sys::SmartMutex<true>> SignalHandlerRegistrationMutex;
  270. sys::SmartScopedLock<true> Guard(*SignalHandlerRegistrationMutex);
  271. // If the handlers are already registered, we're done.
  272. if (NumRegisteredSignals.load() != 0)
  273. return;
  274. // Create an alternate stack for signal handling. This is necessary for us to
  275. // be able to reliably handle signals due to stack overflow.
  276. CreateSigAltStack();
  277. enum class SignalKind { IsKill, IsInfo };
  278. auto registerHandler = [&](int Signal, SignalKind Kind) {
  279. unsigned Index = NumRegisteredSignals.load();
  280. assert(Index < array_lengthof(RegisteredSignalInfo) &&
  281. "Out of space for signal handlers!");
  282. struct sigaction NewHandler;
  283. switch (Kind) {
  284. case SignalKind::IsKill:
  285. NewHandler.sa_handler = SignalHandler;
  286. NewHandler.sa_flags = SA_NODEFER | SA_RESETHAND | SA_ONSTACK;
  287. break;
  288. case SignalKind::IsInfo:
  289. NewHandler.sa_handler = InfoSignalHandler;
  290. NewHandler.sa_flags = SA_ONSTACK;
  291. break;
  292. }
  293. sigemptyset(&NewHandler.sa_mask);
  294. // Install the new handler, save the old one in RegisteredSignalInfo.
  295. sigaction(Signal, &NewHandler, &RegisteredSignalInfo[Index].SA);
  296. RegisteredSignalInfo[Index].SigNo = Signal;
  297. ++NumRegisteredSignals;
  298. };
  299. for (auto S : IntSigs)
  300. registerHandler(S, SignalKind::IsKill);
  301. for (auto S : KillSigs)
  302. registerHandler(S, SignalKind::IsKill);
  303. for (auto S : InfoSigs)
  304. registerHandler(S, SignalKind::IsInfo);
  305. }
  306. static void UnregisterHandlers() {
  307. // Restore all of the signal handlers to how they were before we showed up.
  308. for (unsigned i = 0, e = NumRegisteredSignals.load(); i != e; ++i) {
  309. sigaction(RegisteredSignalInfo[i].SigNo,
  310. &RegisteredSignalInfo[i].SA, nullptr);
  311. --NumRegisteredSignals;
  312. }
  313. }
  314. /// Process the FilesToRemove list.
  315. static void RemoveFilesToRemove() {
  316. FileToRemoveList::removeAllFiles(FilesToRemove);
  317. }
  318. // The signal handler that runs.
  319. static RETSIGTYPE SignalHandler(int Sig) {
  320. // Restore the signal behavior to default, so that the program actually
  321. // crashes when we return and the signal reissues. This also ensures that if
  322. // we crash in our signal handler that the program will terminate immediately
  323. // instead of recursing in the signal handler.
  324. UnregisterHandlers();
  325. // Unmask all potentially blocked kill signals.
  326. sigset_t SigMask;
  327. sigfillset(&SigMask);
  328. sigprocmask(SIG_UNBLOCK, &SigMask, nullptr);
  329. {
  330. RemoveFilesToRemove();
  331. if (std::find(std::begin(IntSigs), std::end(IntSigs), Sig)
  332. != std::end(IntSigs)) {
  333. if (auto OldInterruptFunction = InterruptFunction.exchange(nullptr))
  334. return OldInterruptFunction();
  335. // Send a special return code that drivers can check for, from sysexits.h.
  336. if (Sig == SIGPIPE)
  337. if (SignalHandlerFunctionType CurrentPipeFunction = PipeSignalFunction)
  338. CurrentPipeFunction();
  339. raise(Sig); // Execute the default handler.
  340. return;
  341. }
  342. }
  343. // Otherwise if it is a fault (like SEGV) run any handler.
  344. llvm::sys::RunSignalHandlers();
  345. #ifdef __s390__
  346. // On S/390, certain signals are delivered with PSW Address pointing to
  347. // *after* the faulting instruction. Simply returning from the signal
  348. // handler would continue execution after that point, instead of
  349. // re-raising the signal. Raise the signal manually in those cases.
  350. if (Sig == SIGILL || Sig == SIGFPE || Sig == SIGTRAP)
  351. raise(Sig);
  352. #endif
  353. }
  354. static RETSIGTYPE InfoSignalHandler(int Sig) {
  355. SaveAndRestore<int> SaveErrnoDuringASignalHandler(errno);
  356. if (SignalHandlerFunctionType CurrentInfoFunction = InfoSignalFunction)
  357. CurrentInfoFunction();
  358. }
  359. void llvm::sys::RunInterruptHandlers() {
  360. RemoveFilesToRemove();
  361. }
  362. void llvm::sys::SetInterruptFunction(void (*IF)()) {
  363. InterruptFunction.exchange(IF);
  364. RegisterHandlers();
  365. }
  366. void llvm::sys::SetInfoSignalFunction(void (*Handler)()) {
  367. InfoSignalFunction.exchange(Handler);
  368. RegisterHandlers();
  369. }
  370. void llvm::sys::SetPipeSignalFunction(void (*Handler)()) {
  371. PipeSignalFunction.exchange(Handler);
  372. RegisterHandlers();
  373. }
  374. // The public API
  375. bool llvm::sys::RemoveFileOnSignal(StringRef Filename,
  376. std::string* ErrMsg) {
  377. // Ensure that cleanup will occur as soon as one file is added.
  378. static ManagedStatic<FilesToRemoveCleanup> FilesToRemoveCleanup;
  379. *FilesToRemoveCleanup;
  380. FileToRemoveList::insert(FilesToRemove, Filename.str());
  381. RegisterHandlers();
  382. return false;
  383. }
  384. // The public API
  385. void llvm::sys::DontRemoveFileOnSignal(StringRef Filename) {
  386. FileToRemoveList::erase(FilesToRemove, Filename.str());
  387. }
  388. /// Add a function to be called when a signal is delivered to the process. The
  389. /// handler can have a cookie passed to it to identify what instance of the
  390. /// handler it is.
  391. void llvm::sys::AddSignalHandler(sys::SignalHandlerCallback FnPtr,
  392. void *Cookie) { // Signal-safe.
  393. insertSignalHandler(FnPtr, Cookie);
  394. RegisterHandlers();
  395. }
  396. #if defined(HAVE_BACKTRACE) && ENABLE_BACKTRACES && HAVE_LINK_H && \
  397. (defined(__linux__) || defined(__FreeBSD__) || \
  398. defined(__FreeBSD_kernel__) || defined(__NetBSD__))
  399. struct DlIteratePhdrData {
  400. void **StackTrace;
  401. int depth;
  402. bool first;
  403. const char **modules;
  404. intptr_t *offsets;
  405. const char *main_exec_name;
  406. };
  407. static int dl_iterate_phdr_cb(dl_phdr_info *info, size_t size, void *arg) {
  408. DlIteratePhdrData *data = (DlIteratePhdrData*)arg;
  409. const char *name = data->first ? data->main_exec_name : info->dlpi_name;
  410. data->first = false;
  411. for (int i = 0; i < info->dlpi_phnum; i++) {
  412. const auto *phdr = &info->dlpi_phdr[i];
  413. if (phdr->p_type != PT_LOAD)
  414. continue;
  415. intptr_t beg = info->dlpi_addr + phdr->p_vaddr;
  416. intptr_t end = beg + phdr->p_memsz;
  417. for (int j = 0; j < data->depth; j++) {
  418. if (data->modules[j])
  419. continue;
  420. intptr_t addr = (intptr_t)data->StackTrace[j];
  421. if (beg <= addr && addr < end) {
  422. data->modules[j] = name;
  423. data->offsets[j] = addr - info->dlpi_addr;
  424. }
  425. }
  426. }
  427. return 0;
  428. }
  429. /// If this is an ELF platform, we can find all loaded modules and their virtual
  430. /// addresses with dl_iterate_phdr.
  431. static bool findModulesAndOffsets(void **StackTrace, int Depth,
  432. const char **Modules, intptr_t *Offsets,
  433. const char *MainExecutableName,
  434. StringSaver &StrPool) {
  435. DlIteratePhdrData data = {StackTrace, Depth, true,
  436. Modules, Offsets, MainExecutableName};
  437. dl_iterate_phdr(dl_iterate_phdr_cb, &data);
  438. return true;
  439. }
  440. #else
  441. /// This platform does not have dl_iterate_phdr, so we do not yet know how to
  442. /// find all loaded DSOs.
  443. static bool findModulesAndOffsets(void **StackTrace, int Depth,
  444. const char **Modules, intptr_t *Offsets,
  445. const char *MainExecutableName,
  446. StringSaver &StrPool) {
  447. return false;
  448. }
  449. #endif // defined(HAVE_BACKTRACE) && ENABLE_BACKTRACES && ...
  450. #if ENABLE_BACKTRACES && defined(HAVE__UNWIND_BACKTRACE)
  451. static int unwindBacktrace(void **StackTrace, int MaxEntries) {
  452. if (MaxEntries < 0)
  453. return 0;
  454. // Skip the first frame ('unwindBacktrace' itself).
  455. int Entries = -1;
  456. auto HandleFrame = [&](_Unwind_Context *Context) -> _Unwind_Reason_Code {
  457. // Apparently we need to detect reaching the end of the stack ourselves.
  458. void *IP = (void *)_Unwind_GetIP(Context);
  459. if (!IP)
  460. return _URC_END_OF_STACK;
  461. assert(Entries < MaxEntries && "recursively called after END_OF_STACK?");
  462. if (Entries >= 0)
  463. StackTrace[Entries] = IP;
  464. if (++Entries == MaxEntries)
  465. return _URC_END_OF_STACK;
  466. return _URC_NO_REASON;
  467. };
  468. _Unwind_Backtrace(
  469. [](_Unwind_Context *Context, void *Handler) {
  470. return (*static_cast<decltype(HandleFrame) *>(Handler))(Context);
  471. },
  472. static_cast<void *>(&HandleFrame));
  473. return std::max(Entries, 0);
  474. }
  475. #endif
  476. // In the case of a program crash or fault, print out a stack trace so that the
  477. // user has an indication of why and where we died.
  478. //
  479. // On glibc systems we have the 'backtrace' function, which works nicely, but
  480. // doesn't demangle symbols.
  481. void llvm::sys::PrintStackTrace(raw_ostream &OS) {
  482. #if ENABLE_BACKTRACES
  483. static void *StackTrace[256];
  484. int depth = 0;
  485. #if defined(HAVE_BACKTRACE)
  486. // Use backtrace() to output a backtrace on Linux systems with glibc.
  487. if (!depth)
  488. depth = backtrace(StackTrace, static_cast<int>(array_lengthof(StackTrace)));
  489. #endif
  490. #if defined(HAVE__UNWIND_BACKTRACE)
  491. // Try _Unwind_Backtrace() if backtrace() failed.
  492. if (!depth)
  493. depth = unwindBacktrace(StackTrace,
  494. static_cast<int>(array_lengthof(StackTrace)));
  495. #endif
  496. if (!depth)
  497. return;
  498. if (printSymbolizedStackTrace(Argv0, StackTrace, depth, OS))
  499. return;
  500. #if HAVE_DLFCN_H && HAVE_DLADDR
  501. int width = 0;
  502. for (int i = 0; i < depth; ++i) {
  503. Dl_info dlinfo;
  504. dladdr(StackTrace[i], &dlinfo);
  505. const char* name = strrchr(dlinfo.dli_fname, '/');
  506. int nwidth;
  507. if (!name) nwidth = strlen(dlinfo.dli_fname);
  508. else nwidth = strlen(name) - 1;
  509. if (nwidth > width) width = nwidth;
  510. }
  511. for (int i = 0; i < depth; ++i) {
  512. Dl_info dlinfo;
  513. dladdr(StackTrace[i], &dlinfo);
  514. OS << format("%-2d", i);
  515. const char* name = strrchr(dlinfo.dli_fname, '/');
  516. if (!name) OS << format(" %-*s", width, dlinfo.dli_fname);
  517. else OS << format(" %-*s", width, name+1);
  518. OS << format(" %#0*lx", (int)(sizeof(void*) * 2) + 2,
  519. (unsigned long)StackTrace[i]);
  520. if (dlinfo.dli_sname != nullptr) {
  521. OS << ' ';
  522. int res;
  523. char* d = itaniumDemangle(dlinfo.dli_sname, nullptr, nullptr, &res);
  524. if (!d) OS << dlinfo.dli_sname;
  525. else OS << d;
  526. free(d);
  527. OS << format(" + %tu", (static_cast<const char*>(StackTrace[i])-
  528. static_cast<const char*>(dlinfo.dli_saddr)));
  529. }
  530. OS << '\n';
  531. }
  532. #elif defined(HAVE_BACKTRACE)
  533. backtrace_symbols_fd(StackTrace, depth, STDERR_FILENO);
  534. #endif
  535. #endif
  536. }
  537. static void PrintStackTraceSignalHandler(void *) {
  538. sys::PrintStackTrace(llvm::errs());
  539. }
  540. void llvm::sys::DisableSystemDialogsOnCrash() {}
  541. /// When an error signal (such as SIGABRT or SIGSEGV) is delivered to the
  542. /// process, print a stack trace and then exit.
  543. void llvm::sys::PrintStackTraceOnErrorSignal(StringRef Argv0,
  544. bool DisableCrashReporting) {
  545. ::Argv0 = Argv0;
  546. AddSignalHandler(PrintStackTraceSignalHandler, nullptr);
  547. #if defined(__APPLE__) && ENABLE_CRASH_OVERRIDES
  548. // Environment variable to disable any kind of crash dialog.
  549. if (DisableCrashReporting || getenv("LLVM_DISABLE_CRASH_REPORT")) {
  550. mach_port_t self = mach_task_self();
  551. exception_mask_t mask = EXC_MASK_CRASH;
  552. kern_return_t ret = task_set_exception_ports(self,
  553. mask,
  554. MACH_PORT_NULL,
  555. EXCEPTION_STATE_IDENTITY | MACH_EXCEPTION_CODES,
  556. THREAD_STATE_NONE);
  557. (void)ret;
  558. }
  559. #endif
  560. }