xref: /llvm-project/lldb/source/Utility/LLDBAssert.cpp (revision 96ef428953ed0f2a6c973709005fd17fd18318a1)
1 //===-- LLDBAssert.cpp ----------------------------------------------------===//
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 #include "lldb/Utility/LLDBAssert.h"
10 #include "llvm/Config/llvm-config.h"
11 #include "llvm/Support/FormatVariadic.h"
12 #include "llvm/Support/Signals.h"
13 #include "llvm/Support/raw_ostream.h"
14 
15 #if LLVM_SUPPORT_XCODE_SIGNPOSTS
16 #include <os/log.h>
17 #endif
18 
19 #include <atomic>
20 
21 namespace lldb_private {
22 
23 /// The default callback prints to stderr.
24 static void DefaultAssertCallback(llvm::StringRef message,
25                                   llvm::StringRef backtrace,
26                                   llvm::StringRef prompt) {
27   llvm::errs() << message << '\n';
28   llvm::errs() << backtrace; // Backtrace includes a newline.
29   llvm::errs() << prompt << '\n';
30 }
31 
32 static std::atomic<LLDBAssertCallback> g_lldb_assert_callback =
33     &DefaultAssertCallback;
34 
35 void _lldb_assert(bool expression, const char *expr_text, const char *func,
36                   const char *file, unsigned int line) {
37   if (LLVM_LIKELY(expression))
38     return;
39 
40 #if LLVM_SUPPORT_XCODE_SIGNPOSTS
41   if (__builtin_available(macos 10.12, iOS 10, tvOS 10, watchOS 3, *)) {
42     os_log_fault(OS_LOG_DEFAULT,
43                  "Assertion failed: (%s), function %s, file %s, line %u\n",
44                  expr_text, func, file, line);
45   }
46 #endif
47 
48   std::string buffer;
49   llvm::raw_string_ostream backtrace(buffer);
50   llvm::sys::PrintStackTrace(backtrace);
51 
52   (*g_lldb_assert_callback.load())(
53       llvm::formatv("Assertion failed: ({0}), function {1}, file {2}, line {3}",
54                     expr_text, func, file, line)
55           .str(),
56       buffer,
57       "Please file a bug report against lldb reporting this failure log, and "
58       "as many details as possible");
59 }
60 
61 void SetLLDBAssertCallback(LLDBAssertCallback callback) {
62   g_lldb_assert_callback.exchange(callback);
63 }
64 
65 } // namespace lldb_private
66