1 //===-- ubsan_diag.cc -----------------------------------------------------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // Diagnostic reporting for the UBSan runtime. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "ubsan_platform.h" 15 #if CAN_SANITIZE_UB 16 #include "ubsan_diag.h" 17 #include "ubsan_init.h" 18 #include "ubsan_flags.h" 19 #include "ubsan_monitor.h" 20 #include "sanitizer_common/sanitizer_placement_new.h" 21 #include "sanitizer_common/sanitizer_report_decorator.h" 22 #include "sanitizer_common/sanitizer_stacktrace.h" 23 #include "sanitizer_common/sanitizer_stacktrace_printer.h" 24 #include "sanitizer_common/sanitizer_suppressions.h" 25 #include "sanitizer_common/sanitizer_symbolizer.h" 26 #include <stdio.h> 27 28 using namespace __ubsan; 29 30 void __ubsan::GetStackTrace(BufferedStackTrace *stack, uptr max_depth, uptr pc, 31 uptr bp, void *context, bool fast) { 32 uptr top = 0; 33 uptr bottom = 0; 34 if (fast) 35 GetThreadStackTopAndBottom(false, &top, &bottom); 36 stack->Unwind(max_depth, pc, bp, context, top, bottom, fast); 37 } 38 39 static void MaybePrintStackTrace(uptr pc, uptr bp) { 40 // We assume that flags are already parsed, as UBSan runtime 41 // will definitely be called when we print the first diagnostics message. 42 if (!flags()->print_stacktrace) 43 return; 44 45 BufferedStackTrace stack; 46 GetStackTrace(&stack, kStackTraceMax, pc, bp, nullptr, 47 common_flags()->fast_unwind_on_fatal); 48 stack.Print(); 49 } 50 51 static const char *ConvertTypeToString(ErrorType Type) { 52 switch (Type) { 53 #define UBSAN_CHECK(Name, SummaryKind, FSanitizeFlagName) \ 54 case ErrorType::Name: \ 55 return SummaryKind; 56 #include "ubsan_checks.inc" 57 #undef UBSAN_CHECK 58 } 59 UNREACHABLE("unknown ErrorType!"); 60 } 61 62 static const char *ConvertTypeToFlagName(ErrorType Type) { 63 switch (Type) { 64 #define UBSAN_CHECK(Name, SummaryKind, FSanitizeFlagName) \ 65 case ErrorType::Name: \ 66 return FSanitizeFlagName; 67 #include "ubsan_checks.inc" 68 #undef UBSAN_CHECK 69 } 70 UNREACHABLE("unknown ErrorType!"); 71 } 72 73 static void MaybeReportErrorSummary(Location Loc, ErrorType Type) { 74 if (!common_flags()->print_summary) 75 return; 76 if (!flags()->report_error_type) 77 Type = ErrorType::GenericUB; 78 const char *ErrorKind = ConvertTypeToString(Type); 79 if (Loc.isSourceLocation()) { 80 SourceLocation SLoc = Loc.getSourceLocation(); 81 if (!SLoc.isInvalid()) { 82 AddressInfo AI; 83 AI.file = internal_strdup(SLoc.getFilename()); 84 AI.line = SLoc.getLine(); 85 AI.column = SLoc.getColumn(); 86 AI.function = internal_strdup(""); // Avoid printing ?? as function name. 87 ReportErrorSummary(ErrorKind, AI, GetSanititizerToolName()); 88 AI.Clear(); 89 return; 90 } 91 } else if (Loc.isSymbolizedStack()) { 92 const AddressInfo &AI = Loc.getSymbolizedStack()->info; 93 ReportErrorSummary(ErrorKind, AI, GetSanititizerToolName()); 94 return; 95 } 96 ReportErrorSummary(ErrorKind, GetSanititizerToolName()); 97 } 98 99 namespace { 100 class Decorator : public SanitizerCommonDecorator { 101 public: 102 Decorator() : SanitizerCommonDecorator() {} 103 const char *Highlight() const { return Green(); } 104 const char *Note() const { return Black(); } 105 }; 106 } 107 108 SymbolizedStack *__ubsan::getSymbolizedLocation(uptr PC) { 109 InitAsStandaloneIfNecessary(); 110 return Symbolizer::GetOrInit()->SymbolizePC(PC); 111 } 112 113 Diag &Diag::operator<<(const TypeDescriptor &V) { 114 return AddArg(V.getTypeName()); 115 } 116 117 Diag &Diag::operator<<(const Value &V) { 118 if (V.getType().isSignedIntegerTy()) 119 AddArg(V.getSIntValue()); 120 else if (V.getType().isUnsignedIntegerTy()) 121 AddArg(V.getUIntValue()); 122 else if (V.getType().isFloatTy()) 123 AddArg(V.getFloatValue()); 124 else 125 AddArg("<unknown>"); 126 return *this; 127 } 128 129 /// Hexadecimal printing for numbers too large for Printf to handle directly. 130 static void RenderHex(InternalScopedString *Buffer, UIntMax Val) { 131 #if HAVE_INT128_T 132 Buffer->append("0x%08x%08x%08x%08x", (unsigned int)(Val >> 96), 133 (unsigned int)(Val >> 64), (unsigned int)(Val >> 32), 134 (unsigned int)(Val)); 135 #else 136 UNREACHABLE("long long smaller than 64 bits?"); 137 #endif 138 } 139 140 static void RenderLocation(InternalScopedString *Buffer, Location Loc) { 141 switch (Loc.getKind()) { 142 case Location::LK_Source: { 143 SourceLocation SLoc = Loc.getSourceLocation(); 144 if (SLoc.isInvalid()) 145 Buffer->append("<unknown>"); 146 else 147 RenderSourceLocation(Buffer, SLoc.getFilename(), SLoc.getLine(), 148 SLoc.getColumn(), common_flags()->symbolize_vs_style, 149 common_flags()->strip_path_prefix); 150 return; 151 } 152 case Location::LK_Memory: 153 Buffer->append("%p", Loc.getMemoryLocation()); 154 return; 155 case Location::LK_Symbolized: { 156 const AddressInfo &Info = Loc.getSymbolizedStack()->info; 157 if (Info.file) 158 RenderSourceLocation(Buffer, Info.file, Info.line, Info.column, 159 common_flags()->symbolize_vs_style, 160 common_flags()->strip_path_prefix); 161 else if (Info.module) 162 RenderModuleLocation(Buffer, Info.module, Info.module_offset, 163 Info.module_arch, common_flags()->strip_path_prefix); 164 else 165 Buffer->append("%p", Info.address); 166 return; 167 } 168 case Location::LK_Null: 169 Buffer->append("<unknown>"); 170 return; 171 } 172 } 173 174 static void RenderText(InternalScopedString *Buffer, const char *Message, 175 const Diag::Arg *Args) { 176 for (const char *Msg = Message; *Msg; ++Msg) { 177 if (*Msg != '%') { 178 Buffer->append("%c", *Msg); 179 continue; 180 } 181 const Diag::Arg &A = Args[*++Msg - '0']; 182 switch (A.Kind) { 183 case Diag::AK_String: 184 Buffer->append("%s", A.String); 185 break; 186 case Diag::AK_TypeName: { 187 if (SANITIZER_WINDOWS) 188 // The Windows implementation demangles names early. 189 Buffer->append("'%s'", A.String); 190 else 191 Buffer->append("'%s'", Symbolizer::GetOrInit()->Demangle(A.String)); 192 break; 193 } 194 case Diag::AK_SInt: 195 // 'long long' is guaranteed to be at least 64 bits wide. 196 if (A.SInt >= INT64_MIN && A.SInt <= INT64_MAX) 197 Buffer->append("%lld", (long long)A.SInt); 198 else 199 RenderHex(Buffer, A.SInt); 200 break; 201 case Diag::AK_UInt: 202 if (A.UInt <= UINT64_MAX) 203 Buffer->append("%llu", (unsigned long long)A.UInt); 204 else 205 RenderHex(Buffer, A.UInt); 206 break; 207 case Diag::AK_Float: { 208 // FIXME: Support floating-point formatting in sanitizer_common's 209 // printf, and stop using snprintf here. 210 char FloatBuffer[32]; 211 #if SANITIZER_WINDOWS 212 sprintf_s(FloatBuffer, sizeof(FloatBuffer), "%Lg", (long double)A.Float); 213 #else 214 snprintf(FloatBuffer, sizeof(FloatBuffer), "%Lg", (long double)A.Float); 215 #endif 216 Buffer->append("%s", FloatBuffer); 217 break; 218 } 219 case Diag::AK_Pointer: 220 Buffer->append("%p", A.Pointer); 221 break; 222 } 223 } 224 } 225 226 /// Find the earliest-starting range in Ranges which ends after Loc. 227 static Range *upperBound(MemoryLocation Loc, Range *Ranges, 228 unsigned NumRanges) { 229 Range *Best = 0; 230 for (unsigned I = 0; I != NumRanges; ++I) 231 if (Ranges[I].getEnd().getMemoryLocation() > Loc && 232 (!Best || 233 Best->getStart().getMemoryLocation() > 234 Ranges[I].getStart().getMemoryLocation())) 235 Best = &Ranges[I]; 236 return Best; 237 } 238 239 static inline uptr subtractNoOverflow(uptr LHS, uptr RHS) { 240 return (LHS < RHS) ? 0 : LHS - RHS; 241 } 242 243 static inline uptr addNoOverflow(uptr LHS, uptr RHS) { 244 const uptr Limit = (uptr)-1; 245 return (LHS > Limit - RHS) ? Limit : LHS + RHS; 246 } 247 248 /// Render a snippet of the address space near a location. 249 static void PrintMemorySnippet(const Decorator &Decor, MemoryLocation Loc, 250 Range *Ranges, unsigned NumRanges, 251 const Diag::Arg *Args) { 252 // Show at least the 8 bytes surrounding Loc. 253 const unsigned MinBytesNearLoc = 4; 254 MemoryLocation Min = subtractNoOverflow(Loc, MinBytesNearLoc); 255 MemoryLocation Max = addNoOverflow(Loc, MinBytesNearLoc); 256 MemoryLocation OrigMin = Min; 257 for (unsigned I = 0; I < NumRanges; ++I) { 258 Min = __sanitizer::Min(Ranges[I].getStart().getMemoryLocation(), Min); 259 Max = __sanitizer::Max(Ranges[I].getEnd().getMemoryLocation(), Max); 260 } 261 262 // If we have too many interesting bytes, prefer to show bytes after Loc. 263 const unsigned BytesToShow = 32; 264 if (Max - Min > BytesToShow) 265 Min = __sanitizer::Min(Max - BytesToShow, OrigMin); 266 Max = addNoOverflow(Min, BytesToShow); 267 268 if (!IsAccessibleMemoryRange(Min, Max - Min)) { 269 Printf("<memory cannot be printed>\n"); 270 return; 271 } 272 273 // Emit data. 274 InternalScopedString Buffer(1024); 275 for (uptr P = Min; P != Max; ++P) { 276 unsigned char C = *reinterpret_cast<const unsigned char*>(P); 277 Buffer.append("%s%02x", (P % 8 == 0) ? " " : " ", C); 278 } 279 Buffer.append("\n"); 280 281 // Emit highlights. 282 Buffer.append(Decor.Highlight()); 283 Range *InRange = upperBound(Min, Ranges, NumRanges); 284 for (uptr P = Min; P != Max; ++P) { 285 char Pad = ' ', Byte = ' '; 286 if (InRange && InRange->getEnd().getMemoryLocation() == P) 287 InRange = upperBound(P, Ranges, NumRanges); 288 if (!InRange && P > Loc) 289 break; 290 if (InRange && InRange->getStart().getMemoryLocation() < P) 291 Pad = '~'; 292 if (InRange && InRange->getStart().getMemoryLocation() <= P) 293 Byte = '~'; 294 if (P % 8 == 0) 295 Buffer.append("%c", Pad); 296 Buffer.append("%c", Pad); 297 Buffer.append("%c", P == Loc ? '^' : Byte); 298 Buffer.append("%c", Byte); 299 } 300 Buffer.append("%s\n", Decor.Default()); 301 302 // Go over the line again, and print names for the ranges. 303 InRange = 0; 304 unsigned Spaces = 0; 305 for (uptr P = Min; P != Max; ++P) { 306 if (!InRange || InRange->getEnd().getMemoryLocation() == P) 307 InRange = upperBound(P, Ranges, NumRanges); 308 if (!InRange) 309 break; 310 311 Spaces += (P % 8) == 0 ? 2 : 1; 312 313 if (InRange && InRange->getStart().getMemoryLocation() == P) { 314 while (Spaces--) 315 Buffer.append(" "); 316 RenderText(&Buffer, InRange->getText(), Args); 317 Buffer.append("\n"); 318 // FIXME: We only support naming one range for now! 319 break; 320 } 321 322 Spaces += 2; 323 } 324 325 Printf("%s", Buffer.data()); 326 // FIXME: Print names for anything we can identify within the line: 327 // 328 // * If we can identify the memory itself as belonging to a particular 329 // global, stack variable, or dynamic allocation, then do so. 330 // 331 // * If we have a pointer-size, pointer-aligned range highlighted, 332 // determine whether the value of that range is a pointer to an 333 // entity which we can name, and if so, print that name. 334 // 335 // This needs an external symbolizer, or (preferably) ASan instrumentation. 336 } 337 338 Diag::~Diag() { 339 // All diagnostics should be printed under report mutex. 340 ScopedReport::CheckLocked(); 341 Decorator Decor; 342 InternalScopedString Buffer(1024); 343 344 // Prepare a report that a monitor process can inspect. 345 if (Level == DL_Error) { 346 RenderText(&Buffer, Message, Args); 347 UndefinedBehaviorReport UBR{ConvertTypeToString(ET), Loc, Buffer}; 348 Buffer.clear(); 349 } 350 351 Buffer.append(Decor.Bold()); 352 RenderLocation(&Buffer, Loc); 353 Buffer.append(":"); 354 355 switch (Level) { 356 case DL_Error: 357 Buffer.append("%s runtime error: %s%s", Decor.Warning(), Decor.Default(), 358 Decor.Bold()); 359 break; 360 361 case DL_Note: 362 Buffer.append("%s note: %s", Decor.Note(), Decor.Default()); 363 break; 364 } 365 366 RenderText(&Buffer, Message, Args); 367 368 Buffer.append("%s\n", Decor.Default()); 369 Printf("%s", Buffer.data()); 370 371 if (Loc.isMemoryLocation()) 372 PrintMemorySnippet(Decor, Loc.getMemoryLocation(), Ranges, NumRanges, Args); 373 } 374 375 ScopedReport::Initializer::Initializer() { InitAsStandaloneIfNecessary(); } 376 377 ScopedReport::ScopedReport(ReportOptions Opts, Location SummaryLoc, 378 ErrorType Type) 379 : Opts(Opts), SummaryLoc(SummaryLoc), Type(Type) {} 380 381 ScopedReport::~ScopedReport() { 382 MaybePrintStackTrace(Opts.pc, Opts.bp); 383 MaybeReportErrorSummary(SummaryLoc, Type); 384 if (flags()->halt_on_error) 385 Die(); 386 } 387 388 ALIGNED(64) static char suppression_placeholder[sizeof(SuppressionContext)]; 389 static SuppressionContext *suppression_ctx = nullptr; 390 static const char kVptrCheck[] = "vptr_check"; 391 static const char *kSuppressionTypes[] = { 392 #define UBSAN_CHECK(Name, SummaryKind, FSanitizeFlagName) FSanitizeFlagName, 393 #include "ubsan_checks.inc" 394 #undef UBSAN_CHECK 395 kVptrCheck, 396 }; 397 398 void __ubsan::InitializeSuppressions() { 399 CHECK_EQ(nullptr, suppression_ctx); 400 suppression_ctx = new (suppression_placeholder) // NOLINT 401 SuppressionContext(kSuppressionTypes, ARRAY_SIZE(kSuppressionTypes)); 402 suppression_ctx->ParseFromFile(flags()->suppressions); 403 } 404 405 bool __ubsan::IsVptrCheckSuppressed(const char *TypeName) { 406 InitAsStandaloneIfNecessary(); 407 CHECK(suppression_ctx); 408 Suppression *s; 409 return suppression_ctx->Match(TypeName, kVptrCheck, &s); 410 } 411 412 bool __ubsan::IsPCSuppressed(ErrorType ET, uptr PC, const char *Filename) { 413 InitAsStandaloneIfNecessary(); 414 CHECK(suppression_ctx); 415 const char *SuppType = ConvertTypeToFlagName(ET); 416 // Fast path: don't symbolize PC if there is no suppressions for given UB 417 // type. 418 if (!suppression_ctx->HasSuppressionType(SuppType)) 419 return false; 420 Suppression *s = nullptr; 421 // Suppress by file name known to runtime. 422 if (Filename != nullptr && suppression_ctx->Match(Filename, SuppType, &s)) 423 return true; 424 // Suppress by module name. 425 if (const char *Module = Symbolizer::GetOrInit()->GetModuleNameForPc(PC)) { 426 if (suppression_ctx->Match(Module, SuppType, &s)) 427 return true; 428 } 429 // Suppress by function or source file name from debug info. 430 SymbolizedStackHolder Stack(Symbolizer::GetOrInit()->SymbolizePC(PC)); 431 const AddressInfo &AI = Stack.get()->info; 432 return suppression_ctx->Match(AI.function, SuppType, &s) || 433 suppression_ctx->Match(AI.file, SuppType, &s); 434 } 435 436 #endif // CAN_SANITIZE_UB 437