Signals.inc 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666
  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 void SignalHandler(int Sig); // defined below.
  80. static void 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[] = {SIGHUP, SIGINT, SIGTERM, SIGUSR2};
  193. /// Signals that represent that we have a bug, and our prompt termination has
  194. /// been ordered.
  195. static const int KillSigs[] = {SIGILL,
  196. SIGTRAP,
  197. SIGABRT,
  198. SIGFPE,
  199. SIGBUS,
  200. SIGSEGV,
  201. SIGQUIT
  202. #ifdef SIGSYS
  203. ,
  204. SIGSYS
  205. #endif
  206. #ifdef SIGXCPU
  207. ,
  208. SIGXCPU
  209. #endif
  210. #ifdef SIGXFSZ
  211. ,
  212. SIGXFSZ
  213. #endif
  214. #ifdef SIGEMT
  215. ,
  216. SIGEMT
  217. #endif
  218. };
  219. /// Signals that represent requests for status.
  220. static const int InfoSigs[] = {SIGUSR1
  221. #ifdef SIGINFO
  222. ,
  223. SIGINFO
  224. #endif
  225. };
  226. static const size_t NumSigs = std::size(IntSigs) + std::size(KillSigs) +
  227. std::size(InfoSigs) + 1 /* SIGPIPE */;
  228. static std::atomic<unsigned> NumRegisteredSignals = ATOMIC_VAR_INIT(0);
  229. static struct {
  230. struct sigaction SA;
  231. int SigNo;
  232. } RegisteredSignalInfo[NumSigs];
  233. #if defined(HAVE_SIGALTSTACK)
  234. // Hold onto both the old and new alternate signal stack so that it's not
  235. // reported as a leak. We don't make any attempt to remove our alt signal
  236. // stack if we remove our signal handlers; that can't be done reliably if
  237. // someone else is also trying to do the same thing.
  238. static stack_t OldAltStack;
  239. LLVM_ATTRIBUTE_USED static void *NewAltStackPointer;
  240. static void CreateSigAltStack() {
  241. const size_t AltStackSize = MINSIGSTKSZ + 64 * 1024;
  242. // If we're executing on the alternate stack, or we already have an alternate
  243. // signal stack that we're happy with, there's nothing for us to do. Don't
  244. // reduce the size, some other part of the process might need a larger stack
  245. // than we do.
  246. if (sigaltstack(nullptr, &OldAltStack) != 0 ||
  247. OldAltStack.ss_flags & SS_ONSTACK ||
  248. (OldAltStack.ss_sp && OldAltStack.ss_size >= AltStackSize))
  249. return;
  250. stack_t AltStack = {};
  251. AltStack.ss_sp = static_cast<char *>(safe_malloc(AltStackSize));
  252. NewAltStackPointer = AltStack.ss_sp; // Save to avoid reporting a leak.
  253. AltStack.ss_size = AltStackSize;
  254. if (sigaltstack(&AltStack, &OldAltStack) != 0)
  255. free(AltStack.ss_sp);
  256. }
  257. #else
  258. static void CreateSigAltStack() {}
  259. #endif
  260. static void RegisterHandlers() { // Not signal-safe.
  261. // The mutex prevents other threads from registering handlers while we're
  262. // doing it. We also have to protect the handlers and their count because
  263. // a signal handler could fire while we're registeting handlers.
  264. static ManagedStatic<sys::SmartMutex<true>> SignalHandlerRegistrationMutex;
  265. sys::SmartScopedLock<true> Guard(*SignalHandlerRegistrationMutex);
  266. // If the handlers are already registered, we're done.
  267. if (NumRegisteredSignals.load() != 0)
  268. return;
  269. // Create an alternate stack for signal handling. This is necessary for us to
  270. // be able to reliably handle signals due to stack overflow.
  271. CreateSigAltStack();
  272. enum class SignalKind { IsKill, IsInfo };
  273. auto registerHandler = [&](int Signal, SignalKind Kind) {
  274. unsigned Index = NumRegisteredSignals.load();
  275. assert(Index < std::size(RegisteredSignalInfo) &&
  276. "Out of space for signal handlers!");
  277. struct sigaction NewHandler;
  278. switch (Kind) {
  279. case SignalKind::IsKill:
  280. NewHandler.sa_handler = SignalHandler;
  281. NewHandler.sa_flags = SA_NODEFER | SA_RESETHAND | SA_ONSTACK;
  282. break;
  283. case SignalKind::IsInfo:
  284. NewHandler.sa_handler = InfoSignalHandler;
  285. NewHandler.sa_flags = SA_ONSTACK;
  286. break;
  287. }
  288. sigemptyset(&NewHandler.sa_mask);
  289. // Install the new handler, save the old one in RegisteredSignalInfo.
  290. sigaction(Signal, &NewHandler, &RegisteredSignalInfo[Index].SA);
  291. RegisteredSignalInfo[Index].SigNo = Signal;
  292. ++NumRegisteredSignals;
  293. };
  294. for (auto S : IntSigs)
  295. registerHandler(S, SignalKind::IsKill);
  296. for (auto S : KillSigs)
  297. registerHandler(S, SignalKind::IsKill);
  298. if (OneShotPipeSignalFunction)
  299. registerHandler(SIGPIPE, SignalKind::IsKill);
  300. for (auto S : InfoSigs)
  301. registerHandler(S, SignalKind::IsInfo);
  302. }
  303. void sys::unregisterHandlers() {
  304. // Restore all of the signal handlers to how they were before we showed up.
  305. for (unsigned i = 0, e = NumRegisteredSignals.load(); i != e; ++i) {
  306. sigaction(RegisteredSignalInfo[i].SigNo, &RegisteredSignalInfo[i].SA,
  307. nullptr);
  308. --NumRegisteredSignals;
  309. }
  310. }
  311. /// Process the FilesToRemove list.
  312. static void RemoveFilesToRemove() {
  313. FileToRemoveList::removeAllFiles(FilesToRemove);
  314. }
  315. void sys::CleanupOnSignal(uintptr_t Context) {
  316. int Sig = (int)Context;
  317. if (llvm::is_contained(InfoSigs, Sig)) {
  318. InfoSignalHandler(Sig);
  319. return;
  320. }
  321. RemoveFilesToRemove();
  322. if (llvm::is_contained(IntSigs, Sig) || Sig == SIGPIPE)
  323. return;
  324. llvm::sys::RunSignalHandlers();
  325. }
  326. // The signal handler that runs.
  327. static void SignalHandler(int Sig) {
  328. // Restore the signal behavior to default, so that the program actually
  329. // crashes when we return and the signal reissues. This also ensures that if
  330. // we crash in our signal handler that the program will terminate immediately
  331. // instead of recursing in the signal handler.
  332. sys::unregisterHandlers();
  333. // Unmask all potentially blocked kill signals.
  334. sigset_t SigMask;
  335. sigfillset(&SigMask);
  336. sigprocmask(SIG_UNBLOCK, &SigMask, nullptr);
  337. {
  338. RemoveFilesToRemove();
  339. if (Sig == SIGPIPE)
  340. if (auto OldOneShotPipeFunction =
  341. OneShotPipeSignalFunction.exchange(nullptr))
  342. return OldOneShotPipeFunction();
  343. bool IsIntSig = llvm::is_contained(IntSigs, Sig);
  344. if (IsIntSig)
  345. if (auto OldInterruptFunction = InterruptFunction.exchange(nullptr))
  346. return OldInterruptFunction();
  347. if (Sig == SIGPIPE || IsIntSig) {
  348. raise(Sig); // Execute the default handler.
  349. return;
  350. }
  351. }
  352. // Otherwise if it is a fault (like SEGV) run any handler.
  353. llvm::sys::RunSignalHandlers();
  354. #ifdef __s390__
  355. // On S/390, certain signals are delivered with PSW Address pointing to
  356. // *after* the faulting instruction. Simply returning from the signal
  357. // handler would continue execution after that point, instead of
  358. // re-raising the signal. Raise the signal manually in those cases.
  359. if (Sig == SIGILL || Sig == SIGFPE || Sig == SIGTRAP)
  360. raise(Sig);
  361. #endif
  362. }
  363. static void InfoSignalHandler(int Sig) {
  364. SaveAndRestore SaveErrnoDuringASignalHandler(errno);
  365. if (SignalHandlerFunctionType CurrentInfoFunction = InfoSignalFunction)
  366. CurrentInfoFunction();
  367. }
  368. void llvm::sys::RunInterruptHandlers() { RemoveFilesToRemove(); }
  369. void llvm::sys::SetInterruptFunction(void (*IF)()) {
  370. InterruptFunction.exchange(IF);
  371. RegisterHandlers();
  372. }
  373. void llvm::sys::SetInfoSignalFunction(void (*Handler)()) {
  374. InfoSignalFunction.exchange(Handler);
  375. RegisterHandlers();
  376. }
  377. void llvm::sys::SetOneShotPipeSignalFunction(void (*Handler)()) {
  378. OneShotPipeSignalFunction.exchange(Handler);
  379. RegisterHandlers();
  380. }
  381. void llvm::sys::DefaultOneShotPipeSignalHandler() {
  382. // Send a special return code that drivers can check for, from sysexits.h.
  383. exit(EX_IOERR);
  384. }
  385. // The public API
  386. bool llvm::sys::RemoveFileOnSignal(StringRef Filename, std::string *ErrMsg) {
  387. // Ensure that cleanup will occur as soon as one file is added.
  388. static ManagedStatic<FilesToRemoveCleanup> FilesToRemoveCleanup;
  389. *FilesToRemoveCleanup;
  390. FileToRemoveList::insert(FilesToRemove, Filename.str());
  391. RegisterHandlers();
  392. return false;
  393. }
  394. // The public API
  395. void llvm::sys::DontRemoveFileOnSignal(StringRef Filename) {
  396. FileToRemoveList::erase(FilesToRemove, Filename.str());
  397. }
  398. /// Add a function to be called when a signal is delivered to the process. The
  399. /// handler can have a cookie passed to it to identify what instance of the
  400. /// handler it is.
  401. void llvm::sys::AddSignalHandler(sys::SignalHandlerCallback FnPtr,
  402. void *Cookie) { // Signal-safe.
  403. insertSignalHandler(FnPtr, Cookie);
  404. RegisterHandlers();
  405. }
  406. #if defined(HAVE_BACKTRACE) && ENABLE_BACKTRACES && HAVE_LINK_H && \
  407. (defined(__linux__) || defined(__FreeBSD__) || \
  408. defined(__FreeBSD_kernel__) || defined(__NetBSD__))
  409. struct DlIteratePhdrData {
  410. void **StackTrace;
  411. int depth;
  412. bool first;
  413. const char **modules;
  414. intptr_t *offsets;
  415. const char *main_exec_name;
  416. };
  417. static int dl_iterate_phdr_cb(dl_phdr_info *info, size_t size, void *arg) {
  418. DlIteratePhdrData *data = (DlIteratePhdrData *)arg;
  419. const char *name = data->first ? data->main_exec_name : info->dlpi_name;
  420. data->first = false;
  421. for (int i = 0; i < info->dlpi_phnum; i++) {
  422. const auto *phdr = &info->dlpi_phdr[i];
  423. if (phdr->p_type != PT_LOAD)
  424. continue;
  425. intptr_t beg = info->dlpi_addr + phdr->p_vaddr;
  426. intptr_t end = beg + phdr->p_memsz;
  427. for (int j = 0; j < data->depth; j++) {
  428. if (data->modules[j])
  429. continue;
  430. intptr_t addr = (intptr_t)data->StackTrace[j];
  431. if (beg <= addr && addr < end) {
  432. data->modules[j] = name;
  433. data->offsets[j] = addr - info->dlpi_addr;
  434. }
  435. }
  436. }
  437. return 0;
  438. }
  439. /// If this is an ELF platform, we can find all loaded modules and their virtual
  440. /// addresses with dl_iterate_phdr.
  441. static bool findModulesAndOffsets(void **StackTrace, int Depth,
  442. const char **Modules, intptr_t *Offsets,
  443. const char *MainExecutableName,
  444. StringSaver &StrPool) {
  445. DlIteratePhdrData data = {StackTrace, Depth, true,
  446. Modules, Offsets, MainExecutableName};
  447. dl_iterate_phdr(dl_iterate_phdr_cb, &data);
  448. return true;
  449. }
  450. #else
  451. /// This platform does not have dl_iterate_phdr, so we do not yet know how to
  452. /// find all loaded DSOs.
  453. static bool findModulesAndOffsets(void **StackTrace, int Depth,
  454. const char **Modules, intptr_t *Offsets,
  455. const char *MainExecutableName,
  456. StringSaver &StrPool) {
  457. return false;
  458. }
  459. #endif // defined(HAVE_BACKTRACE) && ENABLE_BACKTRACES && ...
  460. #if ENABLE_BACKTRACES && defined(HAVE__UNWIND_BACKTRACE)
  461. static int unwindBacktrace(void **StackTrace, int MaxEntries) {
  462. if (MaxEntries < 0)
  463. return 0;
  464. // Skip the first frame ('unwindBacktrace' itself).
  465. int Entries = -1;
  466. auto HandleFrame = [&](_Unwind_Context *Context) -> _Unwind_Reason_Code {
  467. // Apparently we need to detect reaching the end of the stack ourselves.
  468. void *IP = (void *)_Unwind_GetIP(Context);
  469. if (!IP)
  470. return _URC_END_OF_STACK;
  471. assert(Entries < MaxEntries && "recursively called after END_OF_STACK?");
  472. if (Entries >= 0)
  473. StackTrace[Entries] = IP;
  474. if (++Entries == MaxEntries)
  475. return _URC_END_OF_STACK;
  476. return _URC_NO_REASON;
  477. };
  478. _Unwind_Backtrace(
  479. [](_Unwind_Context *Context, void *Handler) {
  480. return (*static_cast<decltype(HandleFrame) *>(Handler))(Context);
  481. },
  482. static_cast<void *>(&HandleFrame));
  483. return std::max(Entries, 0);
  484. }
  485. #endif
  486. // In the case of a program crash or fault, print out a stack trace so that the
  487. // user has an indication of why and where we died.
  488. //
  489. // On glibc systems we have the 'backtrace' function, which works nicely, but
  490. // doesn't demangle symbols.
  491. void llvm::sys::PrintStackTrace(raw_ostream &OS, int Depth) {
  492. #if ENABLE_BACKTRACES
  493. static void *StackTrace[256];
  494. int depth = 0;
  495. #if defined(HAVE_BACKTRACE)
  496. // Use backtrace() to output a backtrace on Linux systems with glibc.
  497. if (!depth)
  498. depth = backtrace(StackTrace, static_cast<int>(std::size(StackTrace)));
  499. #endif
  500. #if defined(HAVE__UNWIND_BACKTRACE)
  501. // Try _Unwind_Backtrace() if backtrace() failed.
  502. if (!depth)
  503. depth =
  504. unwindBacktrace(StackTrace, static_cast<int>(std::size(StackTrace)));
  505. #endif
  506. if (!depth)
  507. return;
  508. // If "Depth" is not provided by the caller, use the return value of
  509. // backtrace() for printing a symbolized stack trace.
  510. if (!Depth)
  511. Depth = depth;
  512. if (printSymbolizedStackTrace(Argv0, StackTrace, Depth, OS))
  513. return;
  514. OS << "Stack dump without symbol names (ensure you have llvm-symbolizer in "
  515. "your PATH or set the environment var `LLVM_SYMBOLIZER_PATH` to point "
  516. "to it):\n";
  517. #if HAVE_DLFCN_H && HAVE_DLADDR
  518. int width = 0;
  519. for (int i = 0; i < depth; ++i) {
  520. Dl_info dlinfo;
  521. dladdr(StackTrace[i], &dlinfo);
  522. const char *name = strrchr(dlinfo.dli_fname, '/');
  523. int nwidth;
  524. if (!name)
  525. nwidth = strlen(dlinfo.dli_fname);
  526. else
  527. nwidth = strlen(name) - 1;
  528. if (nwidth > width)
  529. width = nwidth;
  530. }
  531. for (int i = 0; i < depth; ++i) {
  532. Dl_info dlinfo;
  533. dladdr(StackTrace[i], &dlinfo);
  534. OS << format("%-2d", i);
  535. const char *name = strrchr(dlinfo.dli_fname, '/');
  536. if (!name)
  537. OS << format(" %-*s", width, dlinfo.dli_fname);
  538. else
  539. OS << format(" %-*s", width, name + 1);
  540. OS << format(" %#0*lx", (int)(sizeof(void *) * 2) + 2,
  541. (unsigned long)StackTrace[i]);
  542. if (dlinfo.dli_sname != nullptr) {
  543. OS << ' ';
  544. int res;
  545. char *d = itaniumDemangle(dlinfo.dli_sname, nullptr, nullptr, &res);
  546. if (!d)
  547. OS << dlinfo.dli_sname;
  548. else
  549. OS << d;
  550. free(d);
  551. OS << format(" + %tu", (static_cast<const char *>(StackTrace[i]) -
  552. static_cast<const char *>(dlinfo.dli_saddr)));
  553. }
  554. OS << '\n';
  555. }
  556. #elif defined(HAVE_BACKTRACE)
  557. backtrace_symbols_fd(StackTrace, Depth, STDERR_FILENO);
  558. #endif
  559. #endif
  560. }
  561. static void PrintStackTraceSignalHandler(void *) {
  562. sys::PrintStackTrace(llvm::errs());
  563. }
  564. void llvm::sys::DisableSystemDialogsOnCrash() {}
  565. /// When an error signal (such as SIGABRT or SIGSEGV) is delivered to the
  566. /// process, print a stack trace and then exit.
  567. void llvm::sys::PrintStackTraceOnErrorSignal(StringRef Argv0,
  568. bool DisableCrashReporting) {
  569. ::Argv0 = Argv0;
  570. AddSignalHandler(PrintStackTraceSignalHandler, nullptr);
  571. #if defined(__APPLE__) && ENABLE_CRASH_OVERRIDES
  572. // Environment variable to disable any kind of crash dialog.
  573. if (DisableCrashReporting || getenv("LLVM_DISABLE_CRASH_REPORT")) {
  574. mach_port_t self = mach_task_self();
  575. exception_mask_t mask = EXC_MASK_CRASH;
  576. kern_return_t ret = task_set_exception_ports(
  577. self, mask, MACH_PORT_NULL,
  578. EXCEPTION_STATE_IDENTITY | MACH_EXCEPTION_CODES, THREAD_STATE_NONE);
  579. (void)ret;
  580. }
  581. #endif
  582. }