Coverage Report

Created: 2019-07-24 05:18

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