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;
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, int flags) {
92 #if SANITIZER_POSIX && (!SANITIZER_GO && !SANITIZER_ANDROID)
93   int pflags = (PROT_WRITE | PROT_EXEC);
94   if ((prot & pflags) != pflags)
95     return;
96 
97 #  if SANITIZER_APPLE && defined(MAP_JIT)
98   if ((flags & MAP_JIT) == MAP_JIT)
99     return;
100 #  endif
101 
102   ScopedErrorReportLock l;
103   SanitizerCommonDecorator d;
104 
105   InternalMmapVector<BufferedStackTrace> stack_buffer(1);
106   BufferedStackTrace *stack = stack_buffer.data();
107   stack->Reset();
108   uptr top = 0;
109   uptr bottom = 0;
110   GET_CALLER_PC_BP;
111   bool fast = common_flags()->fast_unwind_on_fatal;
112   if (StackTrace::WillUseFastUnwind(fast)) {
113     GetThreadStackTopAndBottom(false, &top, &bottom);
114     stack->Unwind(kStackTraceMax, pc, bp, nullptr, top, bottom, true);
115   } else {
116     stack->Unwind(kStackTraceMax, pc, 0, nullptr, 0, 0, false);
117   }
118 
119   Printf("%s", d.Warning());
120   Report("WARNING: %s: writable-executable page usage\n", SanitizerToolName);
121   Printf("%s", d.Default());
122 
123   stack->Print();
124   ReportErrorSummary("w-and-x-usage", stack);
125 #endif
126 }
127 
128 #if !SANITIZER_FUCHSIA && !SANITIZER_GO
129 void StartReportDeadlySignal() {
130   // Write the first message using fd=2, just in case.
131   // It may actually fail to write in case stderr is closed.
132   CatastrophicErrorWrite(SanitizerToolName, internal_strlen(SanitizerToolName));
133   static const char kDeadlySignal[] = ":DEADLYSIGNAL\n";
134   CatastrophicErrorWrite(kDeadlySignal, sizeof(kDeadlySignal) - 1);
135 }
136 
137 static void MaybeReportNonExecRegion(uptr pc) {
138 #if SANITIZER_FREEBSD || SANITIZER_LINUX || SANITIZER_NETBSD
139   MemoryMappingLayout proc_maps(/*cache_enabled*/ true);
140   MemoryMappedSegment segment;
141   while (proc_maps.Next(&segment)) {
142     if (pc >= segment.start && pc < segment.end && !segment.IsExecutable())
143       Report("Hint: PC is at a non-executable region. Maybe a wild jump?\n");
144   }
145 #endif
146 }
147 
148 static void PrintMemoryByte(InternalScopedString *str, const char *before,
149                             u8 byte) {
150   SanitizerCommonDecorator d;
151   str->append("%s%s%x%x%s ", before, d.MemoryByte(), byte >> 4, byte & 15,
152               d.Default());
153 }
154 
155 static void MaybeDumpInstructionBytes(uptr pc) {
156   if (!common_flags()->dump_instruction_bytes || (pc < GetPageSizeCached()))
157     return;
158   InternalScopedString str;
159   str.append("First 16 instruction bytes at pc: ");
160   if (IsAccessibleMemoryRange(pc, 16)) {
161     for (int i = 0; i < 16; ++i) {
162       PrintMemoryByte(&str, "", ((u8 *)pc)[i]);
163     }
164     str.append("\n");
165   } else {
166     str.append("unaccessible\n");
167   }
168   Report("%s", str.data());
169 }
170 
171 static void MaybeDumpRegisters(void *context) {
172   if (!common_flags()->dump_registers) return;
173   SignalContext::DumpAllRegisters(context);
174 }
175 
176 static void ReportStackOverflowImpl(const SignalContext &sig, u32 tid,
177                                     UnwindSignalStackCallbackType unwind,
178                                     const void *unwind_context) {
179   SanitizerCommonDecorator d;
180   Printf("%s", d.Warning());
181   static const char kDescription[] = "stack-overflow";
182   Report("ERROR: %s: %s on address %p (pc %p bp %p sp %p T%d)\n",
183          SanitizerToolName, kDescription, (void *)sig.addr, (void *)sig.pc,
184          (void *)sig.bp, (void *)sig.sp, tid);
185   Printf("%s", d.Default());
186   InternalMmapVector<BufferedStackTrace> stack_buffer(1);
187   BufferedStackTrace *stack = stack_buffer.data();
188   stack->Reset();
189   unwind(sig, unwind_context, stack);
190   stack->Print();
191   ReportErrorSummary(kDescription, stack);
192 }
193 
194 static void ReportDeadlySignalImpl(const SignalContext &sig, u32 tid,
195                                    UnwindSignalStackCallbackType unwind,
196                                    const void *unwind_context) {
197   SanitizerCommonDecorator d;
198   Printf("%s", d.Warning());
199   const char *description = sig.Describe();
200   if (sig.is_memory_access && !sig.is_true_faulting_addr)
201     Report("ERROR: %s: %s on unknown address (pc %p bp %p sp %p T%d)\n",
202            SanitizerToolName, description, (void *)sig.pc, (void *)sig.bp,
203            (void *)sig.sp, tid);
204   else
205     Report("ERROR: %s: %s on unknown address %p (pc %p bp %p sp %p T%d)\n",
206            SanitizerToolName, description, (void *)sig.addr, (void *)sig.pc,
207            (void *)sig.bp, (void *)sig.sp, tid);
208   Printf("%s", d.Default());
209   if (sig.pc < GetPageSizeCached())
210     Report("Hint: pc points to the zero page.\n");
211   if (sig.is_memory_access) {
212     const char *access_type =
213         sig.write_flag == SignalContext::Write
214             ? "WRITE"
215             : (sig.write_flag == SignalContext::Read ? "READ" : "UNKNOWN");
216     Report("The signal is caused by a %s memory access.\n", access_type);
217     if (!sig.is_true_faulting_addr)
218       Report("Hint: this fault was caused by a dereference of a high value "
219              "address (see register values below).  Disassemble the provided "
220              "pc to learn which register was used.\n");
221     else if (sig.addr < GetPageSizeCached())
222       Report("Hint: address points to the zero page.\n");
223   }
224   MaybeReportNonExecRegion(sig.pc);
225   InternalMmapVector<BufferedStackTrace> stack_buffer(1);
226   BufferedStackTrace *stack = stack_buffer.data();
227   stack->Reset();
228   unwind(sig, unwind_context, stack);
229   stack->Print();
230   MaybeDumpInstructionBytes(sig.pc);
231   MaybeDumpRegisters(sig.context);
232   Printf("%s can not provide additional info.\n", SanitizerToolName);
233   ReportErrorSummary(description, stack);
234 }
235 
236 void ReportDeadlySignal(const SignalContext &sig, u32 tid,
237                         UnwindSignalStackCallbackType unwind,
238                         const void *unwind_context) {
239   if (sig.IsStackOverflow())
240     ReportStackOverflowImpl(sig, tid, unwind, unwind_context);
241   else
242     ReportDeadlySignalImpl(sig, tid, unwind, unwind_context);
243 }
244 
245 void HandleDeadlySignal(void *siginfo, void *context, u32 tid,
246                         UnwindSignalStackCallbackType unwind,
247                         const void *unwind_context) {
248   StartReportDeadlySignal();
249   ScopedErrorReportLock rl;
250   SignalContext sig(siginfo, context);
251   ReportDeadlySignal(sig, tid, unwind, unwind_context);
252   Report("ABORTING\n");
253   Die();
254 }
255 
256 #endif  // !SANITIZER_FUCHSIA && !SANITIZER_GO
257 
258 atomic_uintptr_t ScopedErrorReportLock::reporting_thread_ = {0};
259 StaticSpinMutex ScopedErrorReportLock::mutex_;
260 
261 void ScopedErrorReportLock::Lock() {
262   uptr current = GetThreadSelf();
263   for (;;) {
264     uptr expected = 0;
265     if (atomic_compare_exchange_strong(&reporting_thread_, &expected, current,
266                                        memory_order_relaxed)) {
267       // We've claimed reporting_thread so proceed.
268       mutex_.Lock();
269       return;
270     }
271 
272     if (expected == current) {
273       // This is either asynch signal or nested error during error reporting.
274       // Fail simple to avoid deadlocks in Report().
275 
276       // Can't use Report() here because of potential deadlocks in nested
277       // signal handlers.
278       CatastrophicErrorWrite(SanitizerToolName,
279                              internal_strlen(SanitizerToolName));
280       static const char msg[] = ": nested bug in the same thread, aborting.\n";
281       CatastrophicErrorWrite(msg, sizeof(msg) - 1);
282 
283       internal__exit(common_flags()->exitcode);
284     }
285 
286     internal_sched_yield();
287   }
288 }
289 
290 void ScopedErrorReportLock::Unlock() {
291   mutex_.Unlock();
292   atomic_store_relaxed(&reporting_thread_, 0);
293 }
294 
295 void ScopedErrorReportLock::CheckLocked() { mutex_.CheckLocked(); }
296 
297 }  // namespace __sanitizer
298