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_diag.h" 13 #include "ubsan_init.h" 14 #include "ubsan_flags.h" 15 #include "sanitizer_common/sanitizer_report_decorator.h" 16 #include "sanitizer_common/sanitizer_stacktrace.h" 17 #include "sanitizer_common/sanitizer_stacktrace_printer.h" 18 #include "sanitizer_common/sanitizer_symbolizer.h" 19 #include <stdio.h> 20 21 using namespace __ubsan; 22 23 static void MaybePrintStackTrace(uptr pc, uptr bp) { 24 // We assume that flags are already parsed: InitIfNecessary 25 // will definitely be called when we print the first diagnostics message. 26 if (!flags()->print_stacktrace) 27 return; 28 // We can only use slow unwind, as we don't have any information about stack 29 // top/bottom. 30 // FIXME: It's better to respect "fast_unwind_on_fatal" runtime flag and 31 // fetch stack top/bottom information if we have it (e.g. if we're running 32 // under ASan). 33 if (StackTrace::WillUseFastUnwind(false)) 34 return; 35 BufferedStackTrace stack; 36 stack.Unwind(kStackTraceMax, pc, bp, 0, 0, 0, false); 37 stack.Print(); 38 } 39 40 static void MaybeReportErrorSummary(Location Loc) { 41 if (!common_flags()->print_summary) 42 return; 43 // Don't try to unwind the stack trace in UBSan summaries: just use the 44 // provided location. 45 if (Loc.isSourceLocation()) { 46 SourceLocation SLoc = Loc.getSourceLocation(); 47 if (!SLoc.isInvalid()) { 48 ReportErrorSummary("undefined-behavior", SLoc.getFilename(), 49 SLoc.getLine(), ""); 50 return; 51 } 52 } 53 ReportErrorSummary("undefined-behavior"); 54 } 55 56 namespace { 57 class Decorator : public SanitizerCommonDecorator { 58 public: 59 Decorator() : SanitizerCommonDecorator() {} 60 const char *Highlight() const { return Green(); } 61 const char *EndHighlight() const { return Default(); } 62 const char *Note() const { return Black(); } 63 const char *EndNote() const { return Default(); } 64 }; 65 } 66 67 Location __ubsan::getCallerLocation(uptr CallerLoc) { 68 if (!CallerLoc) 69 return Location(); 70 71 uptr Loc = StackTrace::GetPreviousInstructionPc(CallerLoc); 72 return getFunctionLocation(Loc, 0); 73 } 74 75 Location __ubsan::getFunctionLocation(uptr Loc, const char **FName) { 76 if (!Loc) 77 return Location(); 78 InitIfNecessary(); 79 80 AddressInfo Info; 81 if (!Symbolizer::GetOrInit()->SymbolizePC(Loc, &Info, 1) || !Info.module || 82 !*Info.module) 83 return Location(Loc); 84 85 if (FName && Info.function) 86 *FName = Info.function; 87 88 if (!Info.file) 89 return ModuleLocation(Info.module, Info.module_offset); 90 91 return SourceLocation(Info.file, Info.line, Info.column); 92 } 93 94 Diag &Diag::operator<<(const TypeDescriptor &V) { 95 return AddArg(V.getTypeName()); 96 } 97 98 Diag &Diag::operator<<(const Value &V) { 99 if (V.getType().isSignedIntegerTy()) 100 AddArg(V.getSIntValue()); 101 else if (V.getType().isUnsignedIntegerTy()) 102 AddArg(V.getUIntValue()); 103 else if (V.getType().isFloatTy()) 104 AddArg(V.getFloatValue()); 105 else 106 AddArg("<unknown>"); 107 return *this; 108 } 109 110 /// Hexadecimal printing for numbers too large for Printf to handle directly. 111 static void PrintHex(UIntMax Val) { 112 #if HAVE_INT128_T 113 Printf("0x%08x%08x%08x%08x", 114 (unsigned int)(Val >> 96), 115 (unsigned int)(Val >> 64), 116 (unsigned int)(Val >> 32), 117 (unsigned int)(Val)); 118 #else 119 UNREACHABLE("long long smaller than 64 bits?"); 120 #endif 121 } 122 123 static void renderLocation(Location Loc) { 124 InternalScopedString LocBuffer(1024); 125 switch (Loc.getKind()) { 126 case Location::LK_Source: { 127 SourceLocation SLoc = Loc.getSourceLocation(); 128 if (SLoc.isInvalid()) 129 LocBuffer.append("<unknown>"); 130 else 131 RenderSourceLocation(&LocBuffer, SLoc.getFilename(), SLoc.getLine(), 132 SLoc.getColumn(), common_flags()->strip_path_prefix); 133 break; 134 } 135 case Location::LK_Module: { 136 ModuleLocation MLoc = Loc.getModuleLocation(); 137 RenderModuleLocation(&LocBuffer, MLoc.getModuleName(), MLoc.getOffset(), 138 common_flags()->strip_path_prefix); 139 break; 140 } 141 case Location::LK_Memory: 142 LocBuffer.append("%p", Loc.getMemoryLocation()); 143 break; 144 case Location::LK_Null: 145 LocBuffer.append("<unknown>"); 146 break; 147 } 148 Printf("%s:", LocBuffer.data()); 149 } 150 151 static void renderText(const char *Message, const Diag::Arg *Args) { 152 for (const char *Msg = Message; *Msg; ++Msg) { 153 if (*Msg != '%') { 154 char Buffer[64]; 155 unsigned I; 156 for (I = 0; Msg[I] && Msg[I] != '%' && I != 63; ++I) 157 Buffer[I] = Msg[I]; 158 Buffer[I] = '\0'; 159 Printf(Buffer); 160 Msg += I - 1; 161 } else { 162 const Diag::Arg &A = Args[*++Msg - '0']; 163 switch (A.Kind) { 164 case Diag::AK_String: 165 Printf("%s", A.String); 166 break; 167 case Diag::AK_Mangled: { 168 Printf("'%s'", Symbolizer::GetOrInit()->Demangle(A.String)); 169 break; 170 } 171 case Diag::AK_SInt: 172 // 'long long' is guaranteed to be at least 64 bits wide. 173 if (A.SInt >= INT64_MIN && A.SInt <= INT64_MAX) 174 Printf("%lld", (long long)A.SInt); 175 else 176 PrintHex(A.SInt); 177 break; 178 case Diag::AK_UInt: 179 if (A.UInt <= UINT64_MAX) 180 Printf("%llu", (unsigned long long)A.UInt); 181 else 182 PrintHex(A.UInt); 183 break; 184 case Diag::AK_Float: { 185 // FIXME: Support floating-point formatting in sanitizer_common's 186 // printf, and stop using snprintf here. 187 char Buffer[32]; 188 snprintf(Buffer, sizeof(Buffer), "%Lg", (long double)A.Float); 189 Printf("%s", Buffer); 190 break; 191 } 192 case Diag::AK_Pointer: 193 Printf("%p", A.Pointer); 194 break; 195 } 196 } 197 } 198 } 199 200 /// Find the earliest-starting range in Ranges which ends after Loc. 201 static Range *upperBound(MemoryLocation Loc, Range *Ranges, 202 unsigned NumRanges) { 203 Range *Best = 0; 204 for (unsigned I = 0; I != NumRanges; ++I) 205 if (Ranges[I].getEnd().getMemoryLocation() > Loc && 206 (!Best || 207 Best->getStart().getMemoryLocation() > 208 Ranges[I].getStart().getMemoryLocation())) 209 Best = &Ranges[I]; 210 return Best; 211 } 212 213 static inline uptr subtractNoOverflow(uptr LHS, uptr RHS) { 214 return (LHS < RHS) ? 0 : LHS - RHS; 215 } 216 217 static inline uptr addNoOverflow(uptr LHS, uptr RHS) { 218 const uptr Limit = (uptr)-1; 219 return (LHS > Limit - RHS) ? Limit : LHS + RHS; 220 } 221 222 /// Render a snippet of the address space near a location. 223 static void renderMemorySnippet(const Decorator &Decor, MemoryLocation Loc, 224 Range *Ranges, unsigned NumRanges, 225 const Diag::Arg *Args) { 226 // Show at least the 8 bytes surrounding Loc. 227 const unsigned MinBytesNearLoc = 4; 228 MemoryLocation Min = subtractNoOverflow(Loc, MinBytesNearLoc); 229 MemoryLocation Max = addNoOverflow(Loc, MinBytesNearLoc); 230 MemoryLocation OrigMin = Min; 231 for (unsigned I = 0; I < NumRanges; ++I) { 232 Min = __sanitizer::Min(Ranges[I].getStart().getMemoryLocation(), Min); 233 Max = __sanitizer::Max(Ranges[I].getEnd().getMemoryLocation(), Max); 234 } 235 236 // If we have too many interesting bytes, prefer to show bytes after Loc. 237 const unsigned BytesToShow = 32; 238 if (Max - Min > BytesToShow) 239 Min = __sanitizer::Min(Max - BytesToShow, OrigMin); 240 Max = addNoOverflow(Min, BytesToShow); 241 242 if (!IsAccessibleMemoryRange(Min, Max - Min)) { 243 Printf("<memory cannot be printed>\n"); 244 return; 245 } 246 247 // Emit data. 248 for (uptr P = Min; P != Max; ++P) { 249 unsigned char C = *reinterpret_cast<const unsigned char*>(P); 250 Printf("%s%02x", (P % 8 == 0) ? " " : " ", C); 251 } 252 Printf("\n"); 253 254 // Emit highlights. 255 Printf(Decor.Highlight()); 256 Range *InRange = upperBound(Min, Ranges, NumRanges); 257 for (uptr P = Min; P != Max; ++P) { 258 char Pad = ' ', Byte = ' '; 259 if (InRange && InRange->getEnd().getMemoryLocation() == P) 260 InRange = upperBound(P, Ranges, NumRanges); 261 if (!InRange && P > Loc) 262 break; 263 if (InRange && InRange->getStart().getMemoryLocation() < P) 264 Pad = '~'; 265 if (InRange && InRange->getStart().getMemoryLocation() <= P) 266 Byte = '~'; 267 char Buffer[] = { Pad, Pad, P == Loc ? '^' : Byte, Byte, 0 }; 268 Printf((P % 8 == 0) ? Buffer : &Buffer[1]); 269 } 270 Printf("%s\n", Decor.EndHighlight()); 271 272 // Go over the line again, and print names for the ranges. 273 InRange = 0; 274 unsigned Spaces = 0; 275 for (uptr P = Min; P != Max; ++P) { 276 if (!InRange || InRange->getEnd().getMemoryLocation() == P) 277 InRange = upperBound(P, Ranges, NumRanges); 278 if (!InRange) 279 break; 280 281 Spaces += (P % 8) == 0 ? 2 : 1; 282 283 if (InRange && InRange->getStart().getMemoryLocation() == P) { 284 while (Spaces--) 285 Printf(" "); 286 renderText(InRange->getText(), Args); 287 Printf("\n"); 288 // FIXME: We only support naming one range for now! 289 break; 290 } 291 292 Spaces += 2; 293 } 294 295 // FIXME: Print names for anything we can identify within the line: 296 // 297 // * If we can identify the memory itself as belonging to a particular 298 // global, stack variable, or dynamic allocation, then do so. 299 // 300 // * If we have a pointer-size, pointer-aligned range highlighted, 301 // determine whether the value of that range is a pointer to an 302 // entity which we can name, and if so, print that name. 303 // 304 // This needs an external symbolizer, or (preferably) ASan instrumentation. 305 } 306 307 Diag::~Diag() { 308 // All diagnostics should be printed under report mutex. 309 CommonSanitizerReportMutex.CheckLocked(); 310 Decorator Decor; 311 Printf(Decor.Bold()); 312 313 renderLocation(Loc); 314 315 switch (Level) { 316 case DL_Error: 317 Printf("%s runtime error: %s%s", 318 Decor.Warning(), Decor.EndWarning(), Decor.Bold()); 319 break; 320 321 case DL_Note: 322 Printf("%s note: %s", Decor.Note(), Decor.EndNote()); 323 break; 324 } 325 326 renderText(Message, Args); 327 328 Printf("%s\n", Decor.Default()); 329 330 if (Loc.isMemoryLocation()) 331 renderMemorySnippet(Decor, Loc.getMemoryLocation(), Ranges, 332 NumRanges, Args); 333 } 334 335 ScopedReport::ScopedReport(ReportOptions Opts, Location SummaryLoc) 336 : Opts(Opts), SummaryLoc(SummaryLoc) { 337 InitIfNecessary(); 338 CommonSanitizerReportMutex.Lock(); 339 } 340 341 ScopedReport::~ScopedReport() { 342 MaybePrintStackTrace(Opts.pc, Opts.bp); 343 MaybeReportErrorSummary(SummaryLoc); 344 CommonSanitizerReportMutex.Unlock(); 345 if (Opts.DieAfterReport || flags()->halt_on_error) 346 Die(); 347 } 348 349 bool __ubsan::MatchSuppression(const char *Str, SuppressionType Type) { 350 Suppression *s; 351 // If .preinit_array is not used, it is possible that the UBSan runtime is not 352 // initialized. 353 if (!SANITIZER_CAN_USE_PREINIT_ARRAY) 354 InitIfNecessary(); 355 return SuppressionContext::Get()->Match(Str, Type, &s); 356 } 357