]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_symbolizer_report.cc
Merge r357339 from the clang1000-import branch:
[FreeBSD/FreeBSD.git] / contrib / llvm-project / compiler-rt / lib / sanitizer_common / sanitizer_symbolizer_report.cc
1 //===-- sanitizer_symbolizer_report.cc ------------------------------------===//
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 is shared between AddressSanitizer and other sanitizer run-time
10 /// libraries and implements symbolized reports related functions.
11 ///
12 //===----------------------------------------------------------------------===//
13
14 #include "sanitizer_common.h"
15 #include "sanitizer_file.h"
16 #include "sanitizer_flags.h"
17 #include "sanitizer_procmaps.h"
18 #include "sanitizer_report_decorator.h"
19 #include "sanitizer_stacktrace.h"
20 #include "sanitizer_stacktrace_printer.h"
21 #include "sanitizer_symbolizer.h"
22
23 #if SANITIZER_POSIX
24 # include "sanitizer_posix.h"
25 # include <sys/mman.h>
26 #endif
27
28 namespace __sanitizer {
29
30 #if !SANITIZER_GO
31 void ReportErrorSummary(const char *error_type, const AddressInfo &info,
32                         const char *alt_tool_name) {
33   if (!common_flags()->print_summary) return;
34   InternalScopedString buff(kMaxSummaryLength);
35   buff.append("%s ", error_type);
36   RenderFrame(&buff, "%L %F", 0, info, common_flags()->symbolize_vs_style,
37               common_flags()->strip_path_prefix);
38   ReportErrorSummary(buff.data(), alt_tool_name);
39 }
40 #endif
41
42 #if !SANITIZER_FUCHSIA
43
44 bool ReportFile::SupportsColors() {
45   SpinMutexLock l(mu);
46   ReopenIfNecessary();
47   return SupportsColoredOutput(fd);
48 }
49
50 static INLINE bool ReportSupportsColors() {
51   return report_file.SupportsColors();
52 }
53
54 #else  // SANITIZER_FUCHSIA
55
56 // Fuchsia's logs always go through post-processing that handles colorization.
57 static INLINE bool ReportSupportsColors() { return true; }
58
59 #endif  // !SANITIZER_FUCHSIA
60
61 bool ColorizeReports() {
62   // FIXME: Add proper Windows support to AnsiColorDecorator and re-enable color
63   // printing on Windows.
64   if (SANITIZER_WINDOWS)
65     return false;
66
67   const char *flag = common_flags()->color;
68   return internal_strcmp(flag, "always") == 0 ||
69          (internal_strcmp(flag, "auto") == 0 && ReportSupportsColors());
70 }
71
72 void ReportErrorSummary(const char *error_type, const StackTrace *stack,
73                         const char *alt_tool_name) {
74 #if !SANITIZER_GO
75   if (!common_flags()->print_summary)
76     return;
77   if (stack->size == 0) {
78     ReportErrorSummary(error_type);
79     return;
80   }
81   // Currently, we include the first stack frame into the report summary.
82   // Maybe sometimes we need to choose another frame (e.g. skip memcpy/etc).
83   uptr pc = StackTrace::GetPreviousInstructionPc(stack->trace[0]);
84   SymbolizedStack *frame = Symbolizer::GetOrInit()->SymbolizePC(pc);
85   ReportErrorSummary(error_type, frame->info, alt_tool_name);
86   frame->ClearAll();
87 #endif
88 }
89
90 void ReportMmapWriteExec(int prot) {
91 #if SANITIZER_POSIX && (!SANITIZER_GO && !SANITIZER_ANDROID)
92   if ((prot & (PROT_WRITE | PROT_EXEC)) != (PROT_WRITE | PROT_EXEC))
93     return;
94
95   ScopedErrorReportLock l;
96   SanitizerCommonDecorator d;
97
98   InternalMmapVector<BufferedStackTrace> stack_buffer(1);
99   BufferedStackTrace *stack = stack_buffer.data();
100   stack->Reset();
101   uptr top = 0;
102   uptr bottom = 0;
103   GET_CALLER_PC_BP_SP;
104   (void)sp;
105   bool fast = common_flags()->fast_unwind_on_fatal;
106   if (StackTrace::WillUseFastUnwind(fast)) {
107     GetThreadStackTopAndBottom(false, &top, &bottom);
108     stack->Unwind(kStackTraceMax, pc, bp, nullptr, top, bottom, true);
109   } else
110     stack->Unwind(kStackTraceMax, pc, 0, nullptr, 0, 0, false);
111
112   Printf("%s", d.Warning());
113   Report("WARNING: %s: writable-executable page usage\n", SanitizerToolName);
114   Printf("%s", d.Default());
115
116   stack->Print();
117   ReportErrorSummary("w-and-x-usage", stack);
118 #endif
119 }
120
121 #if !SANITIZER_FUCHSIA && !SANITIZER_RTEMS && !SANITIZER_GO
122 void StartReportDeadlySignal() {
123   // Write the first message using fd=2, just in case.
124   // It may actually fail to write in case stderr is closed.
125   CatastrophicErrorWrite(SanitizerToolName, internal_strlen(SanitizerToolName));
126   static const char kDeadlySignal[] = ":DEADLYSIGNAL\n";
127   CatastrophicErrorWrite(kDeadlySignal, sizeof(kDeadlySignal) - 1);
128 }
129
130 static void MaybeReportNonExecRegion(uptr pc) {
131 #if SANITIZER_FREEBSD || SANITIZER_LINUX || SANITIZER_NETBSD
132   MemoryMappingLayout proc_maps(/*cache_enabled*/ true);
133   MemoryMappedSegment segment;
134   while (proc_maps.Next(&segment)) {
135     if (pc >= segment.start && pc < segment.end && !segment.IsExecutable())
136       Report("Hint: PC is at a non-executable region. Maybe a wild jump?\n");
137   }
138 #endif
139 }
140
141 static void PrintMemoryByte(InternalScopedString *str, const char *before,
142                             u8 byte) {
143   SanitizerCommonDecorator d;
144   str->append("%s%s%x%x%s ", before, d.MemoryByte(), byte >> 4, byte & 15,
145               d.Default());
146 }
147
148 static void MaybeDumpInstructionBytes(uptr pc) {
149   if (!common_flags()->dump_instruction_bytes || (pc < GetPageSizeCached()))
150     return;
151   InternalScopedString str(1024);
152   str.append("First 16 instruction bytes at pc: ");
153   if (IsAccessibleMemoryRange(pc, 16)) {
154     for (int i = 0; i < 16; ++i) {
155       PrintMemoryByte(&str, "", ((u8 *)pc)[i]);
156     }
157     str.append("\n");
158   } else {
159     str.append("unaccessible\n");
160   }
161   Report("%s", str.data());
162 }
163
164 static void MaybeDumpRegisters(void *context) {
165   if (!common_flags()->dump_registers) return;
166   SignalContext::DumpAllRegisters(context);
167 }
168
169 static void ReportStackOverflowImpl(const SignalContext &sig, u32 tid,
170                                     UnwindSignalStackCallbackType unwind,
171                                     const void *unwind_context) {
172   SanitizerCommonDecorator d;
173   Printf("%s", d.Warning());
174   static const char kDescription[] = "stack-overflow";
175   Report("ERROR: %s: %s on address %p (pc %p bp %p sp %p T%d)\n",
176          SanitizerToolName, kDescription, (void *)sig.addr, (void *)sig.pc,
177          (void *)sig.bp, (void *)sig.sp, tid);
178   Printf("%s", d.Default());
179   InternalMmapVector<BufferedStackTrace> stack_buffer(1);
180   BufferedStackTrace *stack = stack_buffer.data();
181   stack->Reset();
182   unwind(sig, unwind_context, stack);
183   stack->Print();
184   ReportErrorSummary(kDescription, stack);
185 }
186
187 static void ReportDeadlySignalImpl(const SignalContext &sig, u32 tid,
188                                    UnwindSignalStackCallbackType unwind,
189                                    const void *unwind_context) {
190   SanitizerCommonDecorator d;
191   Printf("%s", d.Warning());
192   const char *description = sig.Describe();
193   Report("ERROR: %s: %s on unknown address %p (pc %p bp %p sp %p T%d)\n",
194          SanitizerToolName, description, (void *)sig.addr, (void *)sig.pc,
195          (void *)sig.bp, (void *)sig.sp, tid);
196   Printf("%s", d.Default());
197   if (sig.pc < GetPageSizeCached())
198     Report("Hint: pc points to the zero page.\n");
199   if (sig.is_memory_access) {
200     const char *access_type =
201         sig.write_flag == SignalContext::WRITE
202             ? "WRITE"
203             : (sig.write_flag == SignalContext::READ ? "READ" : "UNKNOWN");
204     Report("The signal is caused by a %s memory access.\n", access_type);
205     if (sig.addr < GetPageSizeCached())
206       Report("Hint: address points to the zero page.\n");
207   }
208   MaybeReportNonExecRegion(sig.pc);
209   InternalMmapVector<BufferedStackTrace> stack_buffer(1);
210   BufferedStackTrace *stack = stack_buffer.data();
211   stack->Reset();
212   unwind(sig, unwind_context, stack);
213   stack->Print();
214   MaybeDumpInstructionBytes(sig.pc);
215   MaybeDumpRegisters(sig.context);
216   Printf("%s can not provide additional info.\n", SanitizerToolName);
217   ReportErrorSummary(description, stack);
218 }
219
220 void ReportDeadlySignal(const SignalContext &sig, u32 tid,
221                         UnwindSignalStackCallbackType unwind,
222                         const void *unwind_context) {
223   if (sig.IsStackOverflow())
224     ReportStackOverflowImpl(sig, tid, unwind, unwind_context);
225   else
226     ReportDeadlySignalImpl(sig, tid, unwind, unwind_context);
227 }
228
229 void HandleDeadlySignal(void *siginfo, void *context, u32 tid,
230                         UnwindSignalStackCallbackType unwind,
231                         const void *unwind_context) {
232   StartReportDeadlySignal();
233   ScopedErrorReportLock rl;
234   SignalContext sig(siginfo, context);
235   ReportDeadlySignal(sig, tid, unwind, unwind_context);
236   Report("ABORTING\n");
237   Die();
238 }
239
240 #endif  // !SANITIZER_FUCHSIA && !SANITIZER_GO
241
242 static atomic_uintptr_t reporting_thread = {0};
243 static StaticSpinMutex CommonSanitizerReportMutex;
244
245 ScopedErrorReportLock::ScopedErrorReportLock() {
246   uptr current = GetThreadSelf();
247   for (;;) {
248     uptr expected = 0;
249     if (atomic_compare_exchange_strong(&reporting_thread, &expected, current,
250                                        memory_order_relaxed)) {
251       // We've claimed reporting_thread so proceed.
252       CommonSanitizerReportMutex.Lock();
253       return;
254     }
255
256     if (expected == current) {
257       // This is either asynch signal or nested error during error reporting.
258       // Fail simple to avoid deadlocks in Report().
259
260       // Can't use Report() here because of potential deadlocks in nested
261       // signal handlers.
262       CatastrophicErrorWrite(SanitizerToolName,
263                              internal_strlen(SanitizerToolName));
264       static const char msg[] = ": nested bug in the same thread, aborting.\n";
265       CatastrophicErrorWrite(msg, sizeof(msg) - 1);
266
267       internal__exit(common_flags()->exitcode);
268     }
269
270     internal_sched_yield();
271   }
272 }
273
274 ScopedErrorReportLock::~ScopedErrorReportLock() {
275   CommonSanitizerReportMutex.Unlock();
276   atomic_store_relaxed(&reporting_thread, 0);
277 }
278
279 void ScopedErrorReportLock::CheckLocked() {
280   CommonSanitizerReportMutex.CheckLocked();
281 }
282
283 }  // namespace __sanitizer