Signals.inc 22 KB

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