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