sanitizer_symbolizer_report.cpp 11 KB

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