Path: blob/main/contrib/llvm-project/compiler-rt/lib/ubsan/ubsan_diag.cpp
35233 views
//===-- ubsan_diag.cpp ----------------------------------------------------===//1//2// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.3// See https://llvm.org/LICENSE.txt for license information.4// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception5//6//===----------------------------------------------------------------------===//7//8// Diagnostic reporting for the UBSan runtime.9//10//===----------------------------------------------------------------------===//1112#include "ubsan_platform.h"13#if CAN_SANITIZE_UB14#include "ubsan_diag.h"15#include "ubsan_init.h"16#include "ubsan_flags.h"17#include "ubsan_monitor.h"18#include "sanitizer_common/sanitizer_placement_new.h"19#include "sanitizer_common/sanitizer_report_decorator.h"20#include "sanitizer_common/sanitizer_stacktrace.h"21#include "sanitizer_common/sanitizer_stacktrace_printer.h"22#include "sanitizer_common/sanitizer_suppressions.h"23#include "sanitizer_common/sanitizer_symbolizer.h"24#include <stdio.h>2526using namespace __ubsan;2728// UBSan is combined with runtimes that already provide this functionality29// (e.g., ASan) as well as runtimes that lack it (e.g., scudo). Tried to use30// weak linkage to resolve this issue which is not portable and breaks on31// Windows.32// TODO(yln): This is a temporary workaround. GetStackTrace functions will be33// removed in the future.34void ubsan_GetStackTrace(BufferedStackTrace *stack, uptr max_depth, uptr pc,35uptr bp, void *context, bool request_fast) {36uptr top = 0;37uptr bottom = 0;38GetThreadStackTopAndBottom(false, &top, &bottom);39bool fast = StackTrace::WillUseFastUnwind(request_fast);40stack->Unwind(max_depth, pc, bp, context, top, bottom, fast);41}4243static void MaybePrintStackTrace(uptr pc, uptr bp) {44// We assume that flags are already parsed, as UBSan runtime45// will definitely be called when we print the first diagnostics message.46if (!flags()->print_stacktrace)47return;4849BufferedStackTrace stack;50ubsan_GetStackTrace(&stack, kStackTraceMax, pc, bp, nullptr,51common_flags()->fast_unwind_on_fatal);52stack.Print();53}5455static const char *ConvertTypeToString(ErrorType Type) {56switch (Type) {57#define UBSAN_CHECK(Name, SummaryKind, FSanitizeFlagName) \58case ErrorType::Name: \59return SummaryKind;60#include "ubsan_checks.inc"61#undef UBSAN_CHECK62}63UNREACHABLE("unknown ErrorType!");64}6566static const char *ConvertTypeToFlagName(ErrorType Type) {67switch (Type) {68#define UBSAN_CHECK(Name, SummaryKind, FSanitizeFlagName) \69case ErrorType::Name: \70return FSanitizeFlagName;71#include "ubsan_checks.inc"72#undef UBSAN_CHECK73}74UNREACHABLE("unknown ErrorType!");75}7677static void MaybeReportErrorSummary(Location Loc, ErrorType Type) {78if (!common_flags()->print_summary)79return;80if (!flags()->report_error_type)81Type = ErrorType::GenericUB;82const char *ErrorKind = ConvertTypeToString(Type);83if (Loc.isSourceLocation()) {84SourceLocation SLoc = Loc.getSourceLocation();85if (!SLoc.isInvalid()) {86AddressInfo AI;87AI.file = internal_strdup(SLoc.getFilename());88AI.line = SLoc.getLine();89AI.column = SLoc.getColumn();90AI.function = nullptr;91ReportErrorSummary(ErrorKind, AI, GetSanititizerToolName());92AI.Clear();93return;94}95} else if (Loc.isSymbolizedStack()) {96const AddressInfo &AI = Loc.getSymbolizedStack()->info;97ReportErrorSummary(ErrorKind, AI, GetSanititizerToolName());98return;99}100ReportErrorSummary(ErrorKind, GetSanititizerToolName());101}102103namespace {104class Decorator : public SanitizerCommonDecorator {105public:106Decorator() : SanitizerCommonDecorator() {}107const char *Highlight() const { return Green(); }108const char *Note() const { return Black(); }109};110}111112SymbolizedStack *__ubsan::getSymbolizedLocation(uptr PC) {113InitAsStandaloneIfNecessary();114return Symbolizer::GetOrInit()->SymbolizePC(PC);115}116117Diag &Diag::operator<<(const TypeDescriptor &V) {118return AddArg(V.getTypeName());119}120121Diag &Diag::operator<<(const Value &V) {122if (V.getType().isSignedIntegerTy())123AddArg(V.getSIntValue());124else if (V.getType().isUnsignedIntegerTy())125AddArg(V.getUIntValue());126else if (V.getType().isFloatTy())127AddArg(V.getFloatValue());128else129AddArg("<unknown>");130return *this;131}132133/// Hexadecimal printing for numbers too large for Printf to handle directly.134static void RenderHex(InternalScopedString *Buffer, UIntMax Val) {135#if HAVE_INT128_T136Buffer->AppendF("0x%08x%08x%08x%08x", (unsigned int)(Val >> 96),137(unsigned int)(Val >> 64), (unsigned int)(Val >> 32),138(unsigned int)(Val));139#else140UNREACHABLE("long long smaller than 64 bits?");141#endif142}143144static void RenderLocation(InternalScopedString *Buffer, Location Loc) {145switch (Loc.getKind()) {146case Location::LK_Source: {147SourceLocation SLoc = Loc.getSourceLocation();148if (SLoc.isInvalid())149Buffer->AppendF("<unknown>");150else151StackTracePrinter::GetOrInit()->RenderSourceLocation(152Buffer, SLoc.getFilename(), SLoc.getLine(), SLoc.getColumn(),153common_flags()->symbolize_vs_style,154common_flags()->strip_path_prefix);155return;156}157case Location::LK_Memory:158Buffer->AppendF("%p", reinterpret_cast<void *>(Loc.getMemoryLocation()));159return;160case Location::LK_Symbolized: {161const AddressInfo &Info = Loc.getSymbolizedStack()->info;162if (Info.file)163StackTracePrinter::GetOrInit()->RenderSourceLocation(164Buffer, Info.file, Info.line, Info.column,165common_flags()->symbolize_vs_style,166common_flags()->strip_path_prefix);167else if (Info.module)168StackTracePrinter::GetOrInit()->RenderModuleLocation(169Buffer, Info.module, Info.module_offset, Info.module_arch,170common_flags()->strip_path_prefix);171else172Buffer->AppendF("%p", reinterpret_cast<void *>(Info.address));173return;174}175case Location::LK_Null:176Buffer->AppendF("<unknown>");177return;178}179}180181static void RenderText(InternalScopedString *Buffer, const char *Message,182const Diag::Arg *Args) {183for (const char *Msg = Message; *Msg; ++Msg) {184if (*Msg != '%') {185Buffer->AppendF("%c", *Msg);186continue;187}188const Diag::Arg &A = Args[*++Msg - '0'];189switch (A.Kind) {190case Diag::AK_String:191Buffer->AppendF("%s", A.String);192break;193case Diag::AK_TypeName: {194if (SANITIZER_WINDOWS)195// The Windows implementation demangles names early.196Buffer->AppendF("'%s'", A.String);197else198Buffer->AppendF("'%s'", Symbolizer::GetOrInit()->Demangle(A.String));199break;200}201case Diag::AK_SInt:202// 'long long' is guaranteed to be at least 64 bits wide.203if (A.SInt >= INT64_MIN && A.SInt <= INT64_MAX)204Buffer->AppendF("%lld", (long long)A.SInt);205else206RenderHex(Buffer, A.SInt);207break;208case Diag::AK_UInt:209if (A.UInt <= UINT64_MAX)210Buffer->AppendF("%llu", (unsigned long long)A.UInt);211else212RenderHex(Buffer, A.UInt);213break;214case Diag::AK_Float: {215// FIXME: Support floating-point formatting in sanitizer_common's216// printf, and stop using snprintf here.217char FloatBuffer[32];218#if SANITIZER_WINDOWS219// On MSVC platforms, long doubles are equal to regular doubles.220// In MinGW environments on x86, long doubles are 80 bit, but here,221// we're calling an MS CRT provided printf function which considers222// long doubles to be 64 bit. Just cast the float value to a regular223// double to avoid the potential ambiguity in MinGW mode.224sprintf_s(FloatBuffer, sizeof(FloatBuffer), "%g", (double)A.Float);225#else226snprintf(FloatBuffer, sizeof(FloatBuffer), "%Lg", (long double)A.Float);227#endif228Buffer->Append(FloatBuffer);229break;230}231case Diag::AK_Pointer:232Buffer->AppendF("%p", A.Pointer);233break;234}235}236}237238/// Find the earliest-starting range in Ranges which ends after Loc.239static Range *upperBound(MemoryLocation Loc, Range *Ranges,240unsigned NumRanges) {241Range *Best = 0;242for (unsigned I = 0; I != NumRanges; ++I)243if (Ranges[I].getEnd().getMemoryLocation() > Loc &&244(!Best ||245Best->getStart().getMemoryLocation() >246Ranges[I].getStart().getMemoryLocation()))247Best = &Ranges[I];248return Best;249}250251static inline uptr subtractNoOverflow(uptr LHS, uptr RHS) {252return (LHS < RHS) ? 0 : LHS - RHS;253}254255static inline uptr addNoOverflow(uptr LHS, uptr RHS) {256const uptr Limit = (uptr)-1;257return (LHS > Limit - RHS) ? Limit : LHS + RHS;258}259260/// Render a snippet of the address space near a location.261static void PrintMemorySnippet(const Decorator &Decor, MemoryLocation Loc,262Range *Ranges, unsigned NumRanges,263const Diag::Arg *Args) {264// Show at least the 8 bytes surrounding Loc.265const unsigned MinBytesNearLoc = 4;266MemoryLocation Min = subtractNoOverflow(Loc, MinBytesNearLoc);267MemoryLocation Max = addNoOverflow(Loc, MinBytesNearLoc);268MemoryLocation OrigMin = Min;269for (unsigned I = 0; I < NumRanges; ++I) {270Min = __sanitizer::Min(Ranges[I].getStart().getMemoryLocation(), Min);271Max = __sanitizer::Max(Ranges[I].getEnd().getMemoryLocation(), Max);272}273274// If we have too many interesting bytes, prefer to show bytes after Loc.275const unsigned BytesToShow = 32;276if (Max - Min > BytesToShow)277Min = __sanitizer::Min(Max - BytesToShow, OrigMin);278Max = addNoOverflow(Min, BytesToShow);279280if (!IsAccessibleMemoryRange(Min, Max - Min)) {281Printf("<memory cannot be printed>\n");282return;283}284285// Emit data.286InternalScopedString Buffer;287for (uptr P = Min; P != Max; ++P) {288unsigned char C = *reinterpret_cast<const unsigned char*>(P);289Buffer.AppendF("%s%02x", (P % 8 == 0) ? " " : " ", C);290}291Buffer.AppendF("\n");292293// Emit highlights.294Buffer.Append(Decor.Highlight());295Range *InRange = upperBound(Min, Ranges, NumRanges);296for (uptr P = Min; P != Max; ++P) {297char Pad = ' ', Byte = ' ';298if (InRange && InRange->getEnd().getMemoryLocation() == P)299InRange = upperBound(P, Ranges, NumRanges);300if (!InRange && P > Loc)301break;302if (InRange && InRange->getStart().getMemoryLocation() < P)303Pad = '~';304if (InRange && InRange->getStart().getMemoryLocation() <= P)305Byte = '~';306if (P % 8 == 0)307Buffer.AppendF("%c", Pad);308Buffer.AppendF("%c", Pad);309Buffer.AppendF("%c", P == Loc ? '^' : Byte);310Buffer.AppendF("%c", Byte);311}312Buffer.AppendF("%s\n", Decor.Default());313314// Go over the line again, and print names for the ranges.315InRange = 0;316unsigned Spaces = 0;317for (uptr P = Min; P != Max; ++P) {318if (!InRange || InRange->getEnd().getMemoryLocation() == P)319InRange = upperBound(P, Ranges, NumRanges);320if (!InRange)321break;322323Spaces += (P % 8) == 0 ? 2 : 1;324325if (InRange && InRange->getStart().getMemoryLocation() == P) {326while (Spaces--)327Buffer.AppendF(" ");328RenderText(&Buffer, InRange->getText(), Args);329Buffer.AppendF("\n");330// FIXME: We only support naming one range for now!331break;332}333334Spaces += 2;335}336337Printf("%s", Buffer.data());338// FIXME: Print names for anything we can identify within the line:339//340// * If we can identify the memory itself as belonging to a particular341// global, stack variable, or dynamic allocation, then do so.342//343// * If we have a pointer-size, pointer-aligned range highlighted,344// determine whether the value of that range is a pointer to an345// entity which we can name, and if so, print that name.346//347// This needs an external symbolizer, or (preferably) ASan instrumentation.348}349350Diag::~Diag() {351// All diagnostics should be printed under report mutex.352ScopedReport::CheckLocked();353Decorator Decor;354InternalScopedString Buffer;355356// Prepare a report that a monitor process can inspect.357if (Level == DL_Error) {358RenderText(&Buffer, Message, Args);359UndefinedBehaviorReport UBR{ConvertTypeToString(ET), Loc, Buffer};360Buffer.clear();361}362363Buffer.Append(Decor.Bold());364RenderLocation(&Buffer, Loc);365Buffer.AppendF(":");366367switch (Level) {368case DL_Error:369Buffer.AppendF("%s runtime error: %s%s", Decor.Warning(), Decor.Default(),370Decor.Bold());371break;372373case DL_Note:374Buffer.AppendF("%s note: %s", Decor.Note(), Decor.Default());375break;376}377378RenderText(&Buffer, Message, Args);379380Buffer.AppendF("%s\n", Decor.Default());381Printf("%s", Buffer.data());382383if (Loc.isMemoryLocation())384PrintMemorySnippet(Decor, Loc.getMemoryLocation(), Ranges, NumRanges, Args);385}386387ScopedReport::Initializer::Initializer() { InitAsStandaloneIfNecessary(); }388389ScopedReport::ScopedReport(ReportOptions Opts, Location SummaryLoc,390ErrorType Type)391: Opts(Opts), SummaryLoc(SummaryLoc), Type(Type) {}392393ScopedReport::~ScopedReport() {394MaybePrintStackTrace(Opts.pc, Opts.bp);395MaybeReportErrorSummary(SummaryLoc, Type);396397if (common_flags()->print_module_map >= 2)398DumpProcessMap();399400if (flags()->halt_on_error)401Die();402}403404alignas(64) static char suppression_placeholder[sizeof(SuppressionContext)];405static SuppressionContext *suppression_ctx = nullptr;406static const char kVptrCheck[] = "vptr_check";407static const char *kSuppressionTypes[] = {408#define UBSAN_CHECK(Name, SummaryKind, FSanitizeFlagName) FSanitizeFlagName,409#include "ubsan_checks.inc"410#undef UBSAN_CHECK411kVptrCheck,412};413414void __ubsan::InitializeSuppressions() {415CHECK_EQ(nullptr, suppression_ctx);416suppression_ctx = new (suppression_placeholder)417SuppressionContext(kSuppressionTypes, ARRAY_SIZE(kSuppressionTypes));418suppression_ctx->ParseFromFile(flags()->suppressions);419}420421bool __ubsan::IsVptrCheckSuppressed(const char *TypeName) {422InitAsStandaloneIfNecessary();423CHECK(suppression_ctx);424Suppression *s;425return suppression_ctx->Match(TypeName, kVptrCheck, &s);426}427428bool __ubsan::IsPCSuppressed(ErrorType ET, uptr PC, const char *Filename) {429InitAsStandaloneIfNecessary();430CHECK(suppression_ctx);431const char *SuppType = ConvertTypeToFlagName(ET);432// Fast path: don't symbolize PC if there is no suppressions for given UB433// type.434if (!suppression_ctx->HasSuppressionType(SuppType))435return false;436Suppression *s = nullptr;437// Suppress by file name known to runtime.438if (Filename != nullptr && suppression_ctx->Match(Filename, SuppType, &s))439return true;440// Suppress by module name.441if (const char *Module = Symbolizer::GetOrInit()->GetModuleNameForPc(PC)) {442if (suppression_ctx->Match(Module, SuppType, &s))443return true;444}445// Suppress by function or source file name from debug info.446SymbolizedStackHolder Stack(Symbolizer::GetOrInit()->SymbolizePC(PC));447const AddressInfo &AI = Stack.get()->info;448return suppression_ctx->Match(AI.function, SuppType, &s) ||449suppression_ctx->Match(AI.file, SuppType, &s);450}451452#endif // CAN_SANITIZE_UB453454455