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