1 //===-- asan_report.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 // This file is a part of AddressSanitizer, an address sanity checker. 11 // 12 // This file contains error reporting code. 13 //===----------------------------------------------------------------------===// 14 #include "asan_flags.h" 15 #include "asan_internal.h" 16 #include "asan_mapping.h" 17 #include "asan_report.h" 18 #include "asan_stack.h" 19 #include "asan_thread.h" 20 #include "sanitizer_common/sanitizer_common.h" 21 #include "sanitizer_common/sanitizer_flags.h" 22 #include "sanitizer_common/sanitizer_report_decorator.h" 23 #include "sanitizer_common/sanitizer_stackdepot.h" 24 #include "sanitizer_common/sanitizer_symbolizer.h" 25 26 namespace __asan { 27 28 // -------------------- User-specified callbacks ----------------- {{{1 29 static void (*error_report_callback)(const char*); 30 static char *error_message_buffer = 0; 31 static uptr error_message_buffer_pos = 0; 32 static uptr error_message_buffer_size = 0; 33 34 struct ReportData { 35 uptr pc; 36 uptr sp; 37 uptr bp; 38 uptr addr; 39 bool is_write; 40 uptr access_size; 41 const char *description; 42 }; 43 44 static bool report_happened = false; 45 static ReportData report_data = {}; 46 47 void AppendToErrorMessageBuffer(const char *buffer) { 48 if (error_message_buffer) { 49 uptr length = internal_strlen(buffer); 50 CHECK_GE(error_message_buffer_size, error_message_buffer_pos); 51 uptr remaining = error_message_buffer_size - error_message_buffer_pos; 52 internal_strncpy(error_message_buffer + error_message_buffer_pos, 53 buffer, remaining); 54 error_message_buffer[error_message_buffer_size - 1] = '\0'; 55 // FIXME: reallocate the buffer instead of truncating the message. 56 error_message_buffer_pos += Min(remaining, length); 57 } 58 } 59 60 // ---------------------- Decorator ------------------------------ {{{1 61 class Decorator: public __sanitizer::SanitizerCommonDecorator { 62 public: 63 Decorator() : SanitizerCommonDecorator() { } 64 const char *Access() { return Blue(); } 65 const char *EndAccess() { return Default(); } 66 const char *Location() { return Green(); } 67 const char *EndLocation() { return Default(); } 68 const char *Allocation() { return Magenta(); } 69 const char *EndAllocation() { return Default(); } 70 71 const char *ShadowByte(u8 byte) { 72 switch (byte) { 73 case kAsanHeapLeftRedzoneMagic: 74 case kAsanHeapRightRedzoneMagic: 75 case kAsanArrayCookieMagic: 76 return Red(); 77 case kAsanHeapFreeMagic: 78 return Magenta(); 79 case kAsanStackLeftRedzoneMagic: 80 case kAsanStackMidRedzoneMagic: 81 case kAsanStackRightRedzoneMagic: 82 case kAsanStackPartialRedzoneMagic: 83 return Red(); 84 case kAsanStackAfterReturnMagic: 85 return Magenta(); 86 case kAsanInitializationOrderMagic: 87 return Cyan(); 88 case kAsanUserPoisonedMemoryMagic: 89 case kAsanContiguousContainerOOBMagic: 90 case kAsanAllocaLeftMagic: 91 case kAsanAllocaRightMagic: 92 return Blue(); 93 case kAsanStackUseAfterScopeMagic: 94 return Magenta(); 95 case kAsanGlobalRedzoneMagic: 96 return Red(); 97 case kAsanInternalHeapMagic: 98 return Yellow(); 99 case kAsanIntraObjectRedzone: 100 return Yellow(); 101 default: 102 return Default(); 103 } 104 } 105 const char *EndShadowByte() { return Default(); } 106 const char *MemoryByte() { return Magenta(); } 107 const char *EndMemoryByte() { return Default(); } 108 }; 109 110 // ---------------------- Helper functions ----------------------- {{{1 111 112 static void PrintMemoryByte(InternalScopedString *str, const char *before, 113 u8 byte, bool in_shadow, const char *after = "\n") { 114 Decorator d; 115 str->append("%s%s%x%x%s%s", before, 116 in_shadow ? d.ShadowByte(byte) : d.MemoryByte(), 117 byte >> 4, byte & 15, 118 in_shadow ? d.EndShadowByte() : d.EndMemoryByte(), after); 119 } 120 121 static void PrintShadowByte(InternalScopedString *str, const char *before, 122 u8 byte, const char *after = "\n") { 123 PrintMemoryByte(str, before, byte, /*in_shadow*/true, after); 124 } 125 126 static void PrintShadowBytes(InternalScopedString *str, const char *before, 127 u8 *bytes, u8 *guilty, uptr n) { 128 Decorator d; 129 if (before) str->append("%s%p:", before, bytes); 130 for (uptr i = 0; i < n; i++) { 131 u8 *p = bytes + i; 132 const char *before = 133 p == guilty ? "[" : (p - 1 == guilty && i != 0) ? "" : " "; 134 const char *after = p == guilty ? "]" : ""; 135 PrintShadowByte(str, before, *p, after); 136 } 137 str->append("\n"); 138 } 139 140 static void PrintLegend(InternalScopedString *str) { 141 str->append( 142 "Shadow byte legend (one shadow byte represents %d " 143 "application bytes):\n", 144 (int)SHADOW_GRANULARITY); 145 PrintShadowByte(str, " Addressable: ", 0); 146 str->append(" Partially addressable: "); 147 for (u8 i = 1; i < SHADOW_GRANULARITY; i++) PrintShadowByte(str, "", i, " "); 148 str->append("\n"); 149 PrintShadowByte(str, " Heap left redzone: ", 150 kAsanHeapLeftRedzoneMagic); 151 PrintShadowByte(str, " Heap right redzone: ", 152 kAsanHeapRightRedzoneMagic); 153 PrintShadowByte(str, " Freed heap region: ", kAsanHeapFreeMagic); 154 PrintShadowByte(str, " Stack left redzone: ", 155 kAsanStackLeftRedzoneMagic); 156 PrintShadowByte(str, " Stack mid redzone: ", 157 kAsanStackMidRedzoneMagic); 158 PrintShadowByte(str, " Stack right redzone: ", 159 kAsanStackRightRedzoneMagic); 160 PrintShadowByte(str, " Stack partial redzone: ", 161 kAsanStackPartialRedzoneMagic); 162 PrintShadowByte(str, " Stack after return: ", 163 kAsanStackAfterReturnMagic); 164 PrintShadowByte(str, " Stack use after scope: ", 165 kAsanStackUseAfterScopeMagic); 166 PrintShadowByte(str, " Global redzone: ", kAsanGlobalRedzoneMagic); 167 PrintShadowByte(str, " Global init order: ", 168 kAsanInitializationOrderMagic); 169 PrintShadowByte(str, " Poisoned by user: ", 170 kAsanUserPoisonedMemoryMagic); 171 PrintShadowByte(str, " Container overflow: ", 172 kAsanContiguousContainerOOBMagic); 173 PrintShadowByte(str, " Array cookie: ", 174 kAsanArrayCookieMagic); 175 PrintShadowByte(str, " Intra object redzone: ", 176 kAsanIntraObjectRedzone); 177 PrintShadowByte(str, " ASan internal: ", kAsanInternalHeapMagic); 178 PrintShadowByte(str, " Left alloca redzone: ", kAsanAllocaLeftMagic); 179 PrintShadowByte(str, " Right alloca redzone: ", kAsanAllocaRightMagic); 180 } 181 182 void MaybeDumpInstructionBytes(uptr pc) { 183 if (!flags()->dump_instruction_bytes || (pc < GetPageSizeCached())) 184 return; 185 InternalScopedString str(1024); 186 str.append("First 16 instruction bytes at pc: "); 187 if (IsAccessibleMemoryRange(pc, 16)) { 188 for (int i = 0; i < 16; ++i) { 189 PrintMemoryByte(&str, "", ((u8 *)pc)[i], /*in_shadow*/false, " "); 190 } 191 str.append("\n"); 192 } else { 193 str.append("unaccessible\n"); 194 } 195 Report("%s", str.data()); 196 } 197 198 static void PrintShadowMemoryForAddress(uptr addr) { 199 if (!AddrIsInMem(addr)) return; 200 uptr shadow_addr = MemToShadow(addr); 201 const uptr n_bytes_per_row = 16; 202 uptr aligned_shadow = shadow_addr & ~(n_bytes_per_row - 1); 203 InternalScopedString str(4096 * 8); 204 str.append("Shadow bytes around the buggy address:\n"); 205 for (int i = -5; i <= 5; i++) { 206 const char *prefix = (i == 0) ? "=>" : " "; 207 PrintShadowBytes(&str, prefix, (u8 *)(aligned_shadow + i * n_bytes_per_row), 208 (u8 *)shadow_addr, n_bytes_per_row); 209 } 210 if (flags()->print_legend) PrintLegend(&str); 211 Printf("%s", str.data()); 212 } 213 214 static void PrintZoneForPointer(uptr ptr, uptr zone_ptr, 215 const char *zone_name) { 216 if (zone_ptr) { 217 if (zone_name) { 218 Printf("malloc_zone_from_ptr(%p) = %p, which is %s\n", 219 ptr, zone_ptr, zone_name); 220 } else { 221 Printf("malloc_zone_from_ptr(%p) = %p, which doesn't have a name\n", 222 ptr, zone_ptr); 223 } 224 } else { 225 Printf("malloc_zone_from_ptr(%p) = 0\n", ptr); 226 } 227 } 228 229 static void DescribeThread(AsanThread *t) { 230 if (t) 231 DescribeThread(t->context()); 232 } 233 234 // ---------------------- Address Descriptions ------------------- {{{1 235 236 static bool IsASCII(unsigned char c) { 237 return /*0x00 <= c &&*/ c <= 0x7F; 238 } 239 240 static const char *MaybeDemangleGlobalName(const char *name) { 241 // We can spoil names of globals with C linkage, so use an heuristic 242 // approach to check if the name should be demangled. 243 bool should_demangle = false; 244 if (name[0] == '_' && name[1] == 'Z') 245 should_demangle = true; 246 else if (SANITIZER_WINDOWS && name[0] == '\01' && name[1] == '?') 247 should_demangle = true; 248 249 return should_demangle ? Symbolizer::GetOrInit()->Demangle(name) : name; 250 } 251 252 // Check if the global is a zero-terminated ASCII string. If so, print it. 253 static void PrintGlobalNameIfASCII(InternalScopedString *str, 254 const __asan_global &g) { 255 for (uptr p = g.beg; p < g.beg + g.size - 1; p++) { 256 unsigned char c = *(unsigned char*)p; 257 if (c == '\0' || !IsASCII(c)) return; 258 } 259 if (*(char*)(g.beg + g.size - 1) != '\0') return; 260 str->append(" '%s' is ascii string '%s'\n", MaybeDemangleGlobalName(g.name), 261 (char *)g.beg); 262 } 263 264 static const char *GlobalFilename(const __asan_global &g) { 265 const char *res = g.module_name; 266 // Prefer the filename from source location, if is available. 267 if (g.location) 268 res = g.location->filename; 269 CHECK(res); 270 return res; 271 } 272 273 static void PrintGlobalLocation(InternalScopedString *str, 274 const __asan_global &g) { 275 str->append("%s", GlobalFilename(g)); 276 if (!g.location) 277 return; 278 if (g.location->line_no) 279 str->append(":%d", g.location->line_no); 280 if (g.location->column_no) 281 str->append(":%d", g.location->column_no); 282 } 283 284 bool DescribeAddressRelativeToGlobal(uptr addr, uptr size, 285 const __asan_global &g) { 286 if (!IsAddressNearGlobal(addr, g)) return false; 287 InternalScopedString str(4096); 288 Decorator d; 289 str.append("%s", d.Location()); 290 if (addr < g.beg) { 291 str.append("%p is located %zd bytes to the left", (void *)addr, 292 g.beg - addr); 293 } else if (addr + size > g.beg + g.size) { 294 if (addr < g.beg + g.size) 295 addr = g.beg + g.size; 296 str.append("%p is located %zd bytes to the right", (void *)addr, 297 addr - (g.beg + g.size)); 298 } else { 299 // Can it happen? 300 str.append("%p is located %zd bytes inside", (void *)addr, addr - g.beg); 301 } 302 str.append(" of global variable '%s' defined in '", 303 MaybeDemangleGlobalName(g.name)); 304 PrintGlobalLocation(&str, g); 305 str.append("' (0x%zx) of size %zu\n", g.beg, g.size); 306 str.append("%s", d.EndLocation()); 307 PrintGlobalNameIfASCII(&str, g); 308 Printf("%s", str.data()); 309 return true; 310 } 311 312 bool DescribeAddressIfShadow(uptr addr, AddressDescription *descr, bool print) { 313 if (AddrIsInMem(addr)) 314 return false; 315 const char *area_type = nullptr; 316 if (AddrIsInShadowGap(addr)) area_type = "shadow gap"; 317 else if (AddrIsInHighShadow(addr)) area_type = "high shadow"; 318 else if (AddrIsInLowShadow(addr)) area_type = "low shadow"; 319 if (area_type != nullptr) { 320 if (print) { 321 Printf("Address %p is located in the %s area.\n", addr, area_type); 322 } else { 323 CHECK(descr); 324 descr->region_kind = area_type; 325 } 326 return true; 327 } 328 CHECK(0 && "Address is not in memory and not in shadow?"); 329 return false; 330 } 331 332 // Return " (thread_name) " or an empty string if the name is empty. 333 const char *ThreadNameWithParenthesis(AsanThreadContext *t, char buff[], 334 uptr buff_len) { 335 const char *name = t->name; 336 if (name[0] == '\0') return ""; 337 buff[0] = 0; 338 internal_strncat(buff, " (", 3); 339 internal_strncat(buff, name, buff_len - 4); 340 internal_strncat(buff, ")", 2); 341 return buff; 342 } 343 344 const char *ThreadNameWithParenthesis(u32 tid, char buff[], 345 uptr buff_len) { 346 if (tid == kInvalidTid) return ""; 347 asanThreadRegistry().CheckLocked(); 348 AsanThreadContext *t = GetThreadContextByTidLocked(tid); 349 return ThreadNameWithParenthesis(t, buff, buff_len); 350 } 351 352 static void PrintAccessAndVarIntersection(const StackVarDescr &var, uptr addr, 353 uptr access_size, uptr prev_var_end, 354 uptr next_var_beg) { 355 uptr var_end = var.beg + var.size; 356 uptr addr_end = addr + access_size; 357 const char *pos_descr = 0; 358 // If the variable [var.beg, var_end) is the nearest variable to the 359 // current memory access, indicate it in the log. 360 if (addr >= var.beg) { 361 if (addr_end <= var_end) 362 pos_descr = "is inside"; // May happen if this is a use-after-return. 363 else if (addr < var_end) 364 pos_descr = "partially overflows"; 365 else if (addr_end <= next_var_beg && 366 next_var_beg - addr_end >= addr - var_end) 367 pos_descr = "overflows"; 368 } else { 369 if (addr_end > var.beg) 370 pos_descr = "partially underflows"; 371 else if (addr >= prev_var_end && 372 addr - prev_var_end >= var.beg - addr_end) 373 pos_descr = "underflows"; 374 } 375 InternalScopedString str(1024); 376 str.append(" [%zd, %zd)", var.beg, var_end); 377 // Render variable name. 378 str.append(" '"); 379 for (uptr i = 0; i < var.name_len; ++i) { 380 str.append("%c", var.name_pos[i]); 381 } 382 str.append("'"); 383 if (pos_descr) { 384 Decorator d; 385 // FIXME: we may want to also print the size of the access here, 386 // but in case of accesses generated by memset it may be confusing. 387 str.append("%s <== Memory access at offset %zd %s this variable%s\n", 388 d.Location(), addr, pos_descr, d.EndLocation()); 389 } else { 390 str.append("\n"); 391 } 392 Printf("%s", str.data()); 393 } 394 395 bool ParseFrameDescription(const char *frame_descr, 396 InternalMmapVector<StackVarDescr> *vars) { 397 CHECK(frame_descr); 398 char *p; 399 // This string is created by the compiler and has the following form: 400 // "n alloc_1 alloc_2 ... alloc_n" 401 // where alloc_i looks like "offset size len ObjectName". 402 uptr n_objects = (uptr)internal_simple_strtoll(frame_descr, &p, 10); 403 if (n_objects == 0) 404 return false; 405 406 for (uptr i = 0; i < n_objects; i++) { 407 uptr beg = (uptr)internal_simple_strtoll(p, &p, 10); 408 uptr size = (uptr)internal_simple_strtoll(p, &p, 10); 409 uptr len = (uptr)internal_simple_strtoll(p, &p, 10); 410 if (beg == 0 || size == 0 || *p != ' ') { 411 return false; 412 } 413 p++; 414 StackVarDescr var = {beg, size, p, len}; 415 vars->push_back(var); 416 p += len; 417 } 418 419 return true; 420 } 421 422 bool DescribeAddressIfStack(uptr addr, uptr access_size) { 423 AsanThread *t = FindThreadByStackAddress(addr); 424 if (!t) return false; 425 426 Decorator d; 427 char tname[128]; 428 Printf("%s", d.Location()); 429 Printf("Address %p is located in stack of thread T%d%s", addr, t->tid(), 430 ThreadNameWithParenthesis(t->tid(), tname, sizeof(tname))); 431 432 // Try to fetch precise stack frame for this access. 433 AsanThread::StackFrameAccess access; 434 if (!t->GetStackFrameAccessByAddr(addr, &access)) { 435 Printf("%s\n", d.EndLocation()); 436 return true; 437 } 438 Printf(" at offset %zu in frame%s\n", access.offset, d.EndLocation()); 439 440 // Now we print the frame where the alloca has happened. 441 // We print this frame as a stack trace with one element. 442 // The symbolizer may print more than one frame if inlining was involved. 443 // The frame numbers may be different than those in the stack trace printed 444 // previously. That's unfortunate, but I have no better solution, 445 // especially given that the alloca may be from entirely different place 446 // (e.g. use-after-scope, or different thread's stack). 447 #if defined(__powerpc64__) && defined(__BIG_ENDIAN__) 448 // On PowerPC64 ELFv1, the address of a function actually points to a 449 // three-doubleword data structure with the first field containing 450 // the address of the function's code. 451 access.frame_pc = *reinterpret_cast<uptr *>(access.frame_pc); 452 #endif 453 access.frame_pc += 16; 454 Printf("%s", d.EndLocation()); 455 StackTrace alloca_stack(&access.frame_pc, 1); 456 alloca_stack.Print(); 457 458 InternalMmapVector<StackVarDescr> vars(16); 459 if (!ParseFrameDescription(access.frame_descr, &vars)) { 460 Printf("AddressSanitizer can't parse the stack frame " 461 "descriptor: |%s|\n", access.frame_descr); 462 // 'addr' is a stack address, so return true even if we can't parse frame 463 return true; 464 } 465 uptr n_objects = vars.size(); 466 // Report the number of stack objects. 467 Printf(" This frame has %zu object(s):\n", n_objects); 468 469 // Report all objects in this frame. 470 for (uptr i = 0; i < n_objects; i++) { 471 uptr prev_var_end = i ? vars[i - 1].beg + vars[i - 1].size : 0; 472 uptr next_var_beg = i + 1 < n_objects ? vars[i + 1].beg : ~(0UL); 473 PrintAccessAndVarIntersection(vars[i], access.offset, access_size, 474 prev_var_end, next_var_beg); 475 } 476 Printf("HINT: this may be a false positive if your program uses " 477 "some custom stack unwind mechanism or swapcontext\n"); 478 if (SANITIZER_WINDOWS) 479 Printf(" (longjmp, SEH and C++ exceptions *are* supported)\n"); 480 else 481 Printf(" (longjmp and C++ exceptions *are* supported)\n"); 482 483 DescribeThread(t); 484 return true; 485 } 486 487 static void DescribeAccessToHeapChunk(AsanChunkView chunk, uptr addr, 488 uptr access_size) { 489 sptr offset; 490 Decorator d; 491 InternalScopedString str(4096); 492 str.append("%s", d.Location()); 493 if (chunk.AddrIsAtLeft(addr, access_size, &offset)) { 494 str.append("%p is located %zd bytes to the left of", (void *)addr, offset); 495 } else if (chunk.AddrIsAtRight(addr, access_size, &offset)) { 496 if (offset < 0) { 497 addr -= offset; 498 offset = 0; 499 } 500 str.append("%p is located %zd bytes to the right of", (void *)addr, offset); 501 } else if (chunk.AddrIsInside(addr, access_size, &offset)) { 502 str.append("%p is located %zd bytes inside of", (void*)addr, offset); 503 } else { 504 str.append("%p is located somewhere around (this is AddressSanitizer bug!)", 505 (void *)addr); 506 } 507 str.append(" %zu-byte region [%p,%p)\n", chunk.UsedSize(), 508 (void *)(chunk.Beg()), (void *)(chunk.End())); 509 str.append("%s", d.EndLocation()); 510 Printf("%s", str.data()); 511 } 512 513 void DescribeHeapAddress(uptr addr, uptr access_size) { 514 AsanChunkView chunk = FindHeapChunkByAddress(addr); 515 if (!chunk.IsValid()) { 516 Printf("AddressSanitizer can not describe address in more detail " 517 "(wild memory access suspected).\n"); 518 return; 519 } 520 DescribeAccessToHeapChunk(chunk, addr, access_size); 521 CHECK(chunk.AllocTid() != kInvalidTid); 522 asanThreadRegistry().CheckLocked(); 523 AsanThreadContext *alloc_thread = 524 GetThreadContextByTidLocked(chunk.AllocTid()); 525 StackTrace alloc_stack = chunk.GetAllocStack(); 526 char tname[128]; 527 Decorator d; 528 AsanThreadContext *free_thread = 0; 529 if (chunk.FreeTid() != kInvalidTid) { 530 free_thread = GetThreadContextByTidLocked(chunk.FreeTid()); 531 Printf("%sfreed by thread T%d%s here:%s\n", d.Allocation(), 532 free_thread->tid, 533 ThreadNameWithParenthesis(free_thread, tname, sizeof(tname)), 534 d.EndAllocation()); 535 StackTrace free_stack = chunk.GetFreeStack(); 536 free_stack.Print(); 537 Printf("%spreviously allocated by thread T%d%s here:%s\n", 538 d.Allocation(), alloc_thread->tid, 539 ThreadNameWithParenthesis(alloc_thread, tname, sizeof(tname)), 540 d.EndAllocation()); 541 } else { 542 Printf("%sallocated by thread T%d%s here:%s\n", d.Allocation(), 543 alloc_thread->tid, 544 ThreadNameWithParenthesis(alloc_thread, tname, sizeof(tname)), 545 d.EndAllocation()); 546 } 547 alloc_stack.Print(); 548 DescribeThread(GetCurrentThread()); 549 if (free_thread) 550 DescribeThread(free_thread); 551 DescribeThread(alloc_thread); 552 } 553 554 void DescribeAddress(uptr addr, uptr access_size) { 555 // Check if this is shadow or shadow gap. 556 if (DescribeAddressIfShadow(addr)) 557 return; 558 CHECK(AddrIsInMem(addr)); 559 if (DescribeAddressIfGlobal(addr, access_size)) 560 return; 561 if (DescribeAddressIfStack(addr, access_size)) 562 return; 563 // Assume it is a heap address. 564 DescribeHeapAddress(addr, access_size); 565 } 566 567 // ------------------- Thread description -------------------- {{{1 568 569 void DescribeThread(AsanThreadContext *context) { 570 CHECK(context); 571 asanThreadRegistry().CheckLocked(); 572 // No need to announce the main thread. 573 if (context->tid == 0 || context->announced) { 574 return; 575 } 576 context->announced = true; 577 char tname[128]; 578 InternalScopedString str(1024); 579 str.append("Thread T%d%s", context->tid, 580 ThreadNameWithParenthesis(context->tid, tname, sizeof(tname))); 581 if (context->parent_tid == kInvalidTid) { 582 str.append(" created by unknown thread\n"); 583 Printf("%s", str.data()); 584 return; 585 } 586 str.append( 587 " created by T%d%s here:\n", context->parent_tid, 588 ThreadNameWithParenthesis(context->parent_tid, tname, sizeof(tname))); 589 Printf("%s", str.data()); 590 StackDepotGet(context->stack_id).Print(); 591 // Recursively described parent thread if needed. 592 if (flags()->print_full_thread_history) { 593 AsanThreadContext *parent_context = 594 GetThreadContextByTidLocked(context->parent_tid); 595 DescribeThread(parent_context); 596 } 597 } 598 599 // -------------------- Different kinds of reports ----------------- {{{1 600 601 // Use ScopedInErrorReport to run common actions just before and 602 // immediately after printing error report. 603 class ScopedInErrorReport { 604 public: 605 explicit ScopedInErrorReport(ReportData *report = nullptr) { 606 static atomic_uint32_t num_calls; 607 static u32 reporting_thread_tid; 608 if (atomic_fetch_add(&num_calls, 1, memory_order_relaxed) != 0) { 609 // Do not print more than one report, otherwise they will mix up. 610 // Error reporting functions shouldn't return at this situation, as 611 // they are defined as no-return. 612 Report("AddressSanitizer: while reporting a bug found another one. " 613 "Ignoring.\n"); 614 u32 current_tid = GetCurrentTidOrInvalid(); 615 if (current_tid != reporting_thread_tid) { 616 // ASan found two bugs in different threads simultaneously. Sleep 617 // long enough to make sure that the thread which started to print 618 // an error report will finish doing it. 619 SleepForSeconds(Max(100, flags()->sleep_before_dying + 1)); 620 } 621 // If we're still not dead for some reason, use raw _exit() instead of 622 // Die() to bypass any additional checks. 623 internal__exit(flags()->exitcode); 624 } 625 if (report) report_data = *report; 626 report_happened = true; 627 ASAN_ON_ERROR(); 628 // Make sure the registry and sanitizer report mutexes are locked while 629 // we're printing an error report. 630 // We can lock them only here to avoid self-deadlock in case of 631 // recursive reports. 632 asanThreadRegistry().Lock(); 633 CommonSanitizerReportMutex.Lock(); 634 reporting_thread_tid = GetCurrentTidOrInvalid(); 635 Printf("====================================================" 636 "=============\n"); 637 } 638 // Destructor is NORETURN, as functions that report errors are. 639 NORETURN ~ScopedInErrorReport() { 640 // Make sure the current thread is announced. 641 DescribeThread(GetCurrentThread()); 642 // We may want to grab this lock again when printing stats. 643 asanThreadRegistry().Unlock(); 644 // Print memory stats. 645 if (flags()->print_stats) 646 __asan_print_accumulated_stats(); 647 if (error_report_callback) { 648 error_report_callback(error_message_buffer); 649 } 650 Report("ABORTING\n"); 651 Die(); 652 } 653 }; 654 655 void ReportStackOverflow(const SignalContext &sig) { 656 ScopedInErrorReport in_report; 657 Decorator d; 658 Printf("%s", d.Warning()); 659 Report( 660 "ERROR: AddressSanitizer: stack-overflow on address %p" 661 " (pc %p bp %p sp %p T%d)\n", 662 (void *)sig.addr, (void *)sig.pc, (void *)sig.bp, (void *)sig.sp, 663 GetCurrentTidOrInvalid()); 664 Printf("%s", d.EndWarning()); 665 GET_STACK_TRACE_SIGNAL(sig); 666 stack.Print(); 667 ReportErrorSummary("stack-overflow", &stack); 668 } 669 670 void ReportSIGSEGV(const char *description, const SignalContext &sig) { 671 ScopedInErrorReport in_report; 672 Decorator d; 673 Printf("%s", d.Warning()); 674 Report( 675 "ERROR: AddressSanitizer: %s on unknown address %p" 676 " (pc %p bp %p sp %p T%d)\n", 677 description, (void *)sig.addr, (void *)sig.pc, (void *)sig.bp, 678 (void *)sig.sp, GetCurrentTidOrInvalid()); 679 if (sig.pc < GetPageSizeCached()) { 680 Report("Hint: pc points to the zero page.\n"); 681 } 682 Printf("%s", d.EndWarning()); 683 GET_STACK_TRACE_SIGNAL(sig); 684 stack.Print(); 685 MaybeDumpInstructionBytes(sig.pc); 686 Printf("AddressSanitizer can not provide additional info.\n"); 687 ReportErrorSummary("SEGV", &stack); 688 } 689 690 void ReportDoubleFree(uptr addr, BufferedStackTrace *free_stack) { 691 ScopedInErrorReport in_report; 692 Decorator d; 693 Printf("%s", d.Warning()); 694 char tname[128]; 695 u32 curr_tid = GetCurrentTidOrInvalid(); 696 Report("ERROR: AddressSanitizer: attempting double-free on %p in " 697 "thread T%d%s:\n", 698 addr, curr_tid, 699 ThreadNameWithParenthesis(curr_tid, tname, sizeof(tname))); 700 Printf("%s", d.EndWarning()); 701 CHECK_GT(free_stack->size, 0); 702 GET_STACK_TRACE_FATAL(free_stack->trace[0], free_stack->top_frame_bp); 703 stack.Print(); 704 DescribeHeapAddress(addr, 1); 705 ReportErrorSummary("double-free", &stack); 706 } 707 708 void ReportNewDeleteSizeMismatch(uptr addr, uptr delete_size, 709 BufferedStackTrace *free_stack) { 710 ScopedInErrorReport in_report; 711 Decorator d; 712 Printf("%s", d.Warning()); 713 char tname[128]; 714 u32 curr_tid = GetCurrentTidOrInvalid(); 715 Report("ERROR: AddressSanitizer: new-delete-type-mismatch on %p in " 716 "thread T%d%s:\n", 717 addr, curr_tid, 718 ThreadNameWithParenthesis(curr_tid, tname, sizeof(tname))); 719 Printf("%s object passed to delete has wrong type:\n", d.EndWarning()); 720 Printf(" size of the allocated type: %zd bytes;\n" 721 " size of the deallocated type: %zd bytes.\n", 722 asan_mz_size(reinterpret_cast<void*>(addr)), delete_size); 723 CHECK_GT(free_stack->size, 0); 724 GET_STACK_TRACE_FATAL(free_stack->trace[0], free_stack->top_frame_bp); 725 stack.Print(); 726 DescribeHeapAddress(addr, 1); 727 ReportErrorSummary("new-delete-type-mismatch", &stack); 728 Report("HINT: if you don't care about these warnings you may set " 729 "ASAN_OPTIONS=new_delete_type_mismatch=0\n"); 730 } 731 732 void ReportFreeNotMalloced(uptr addr, BufferedStackTrace *free_stack) { 733 ScopedInErrorReport in_report; 734 Decorator d; 735 Printf("%s", d.Warning()); 736 char tname[128]; 737 u32 curr_tid = GetCurrentTidOrInvalid(); 738 Report("ERROR: AddressSanitizer: attempting free on address " 739 "which was not malloc()-ed: %p in thread T%d%s\n", addr, 740 curr_tid, ThreadNameWithParenthesis(curr_tid, tname, sizeof(tname))); 741 Printf("%s", d.EndWarning()); 742 CHECK_GT(free_stack->size, 0); 743 GET_STACK_TRACE_FATAL(free_stack->trace[0], free_stack->top_frame_bp); 744 stack.Print(); 745 DescribeHeapAddress(addr, 1); 746 ReportErrorSummary("bad-free", &stack); 747 } 748 749 void ReportAllocTypeMismatch(uptr addr, BufferedStackTrace *free_stack, 750 AllocType alloc_type, 751 AllocType dealloc_type) { 752 static const char *alloc_names[] = 753 {"INVALID", "malloc", "operator new", "operator new []"}; 754 static const char *dealloc_names[] = 755 {"INVALID", "free", "operator delete", "operator delete []"}; 756 CHECK_NE(alloc_type, dealloc_type); 757 ScopedInErrorReport in_report; 758 Decorator d; 759 Printf("%s", d.Warning()); 760 Report("ERROR: AddressSanitizer: alloc-dealloc-mismatch (%s vs %s) on %p\n", 761 alloc_names[alloc_type], dealloc_names[dealloc_type], addr); 762 Printf("%s", d.EndWarning()); 763 CHECK_GT(free_stack->size, 0); 764 GET_STACK_TRACE_FATAL(free_stack->trace[0], free_stack->top_frame_bp); 765 stack.Print(); 766 DescribeHeapAddress(addr, 1); 767 ReportErrorSummary("alloc-dealloc-mismatch", &stack); 768 Report("HINT: if you don't care about these warnings you may set " 769 "ASAN_OPTIONS=alloc_dealloc_mismatch=0\n"); 770 } 771 772 void ReportMallocUsableSizeNotOwned(uptr addr, BufferedStackTrace *stack) { 773 ScopedInErrorReport in_report; 774 Decorator d; 775 Printf("%s", d.Warning()); 776 Report("ERROR: AddressSanitizer: attempting to call " 777 "malloc_usable_size() for pointer which is " 778 "not owned: %p\n", addr); 779 Printf("%s", d.EndWarning()); 780 stack->Print(); 781 DescribeHeapAddress(addr, 1); 782 ReportErrorSummary("bad-malloc_usable_size", stack); 783 } 784 785 void ReportSanitizerGetAllocatedSizeNotOwned(uptr addr, 786 BufferedStackTrace *stack) { 787 ScopedInErrorReport in_report; 788 Decorator d; 789 Printf("%s", d.Warning()); 790 Report("ERROR: AddressSanitizer: attempting to call " 791 "__sanitizer_get_allocated_size() for pointer which is " 792 "not owned: %p\n", addr); 793 Printf("%s", d.EndWarning()); 794 stack->Print(); 795 DescribeHeapAddress(addr, 1); 796 ReportErrorSummary("bad-__sanitizer_get_allocated_size", stack); 797 } 798 799 void ReportStringFunctionMemoryRangesOverlap(const char *function, 800 const char *offset1, uptr length1, 801 const char *offset2, uptr length2, 802 BufferedStackTrace *stack) { 803 ScopedInErrorReport in_report; 804 Decorator d; 805 char bug_type[100]; 806 internal_snprintf(bug_type, sizeof(bug_type), "%s-param-overlap", function); 807 Printf("%s", d.Warning()); 808 Report("ERROR: AddressSanitizer: %s: " 809 "memory ranges [%p,%p) and [%p, %p) overlap\n", \ 810 bug_type, offset1, offset1 + length1, offset2, offset2 + length2); 811 Printf("%s", d.EndWarning()); 812 stack->Print(); 813 DescribeAddress((uptr)offset1, length1); 814 DescribeAddress((uptr)offset2, length2); 815 ReportErrorSummary(bug_type, stack); 816 } 817 818 void ReportStringFunctionSizeOverflow(uptr offset, uptr size, 819 BufferedStackTrace *stack) { 820 ScopedInErrorReport in_report; 821 Decorator d; 822 const char *bug_type = "negative-size-param"; 823 Printf("%s", d.Warning()); 824 Report("ERROR: AddressSanitizer: %s: (size=%zd)\n", bug_type, size); 825 Printf("%s", d.EndWarning()); 826 stack->Print(); 827 DescribeAddress(offset, size); 828 ReportErrorSummary(bug_type, stack); 829 } 830 831 void ReportBadParamsToAnnotateContiguousContainer(uptr beg, uptr end, 832 uptr old_mid, uptr new_mid, 833 BufferedStackTrace *stack) { 834 ScopedInErrorReport in_report; 835 Report("ERROR: AddressSanitizer: bad parameters to " 836 "__sanitizer_annotate_contiguous_container:\n" 837 " beg : %p\n" 838 " end : %p\n" 839 " old_mid : %p\n" 840 " new_mid : %p\n", 841 beg, end, old_mid, new_mid); 842 uptr granularity = SHADOW_GRANULARITY; 843 if (!IsAligned(beg, granularity)) 844 Report("ERROR: beg is not aligned by %d\n", granularity); 845 stack->Print(); 846 ReportErrorSummary("bad-__sanitizer_annotate_contiguous_container", stack); 847 } 848 849 void ReportODRViolation(const __asan_global *g1, u32 stack_id1, 850 const __asan_global *g2, u32 stack_id2) { 851 ScopedInErrorReport in_report; 852 Decorator d; 853 Printf("%s", d.Warning()); 854 Report("ERROR: AddressSanitizer: odr-violation (%p):\n", g1->beg); 855 Printf("%s", d.EndWarning()); 856 InternalScopedString g1_loc(256), g2_loc(256); 857 PrintGlobalLocation(&g1_loc, *g1); 858 PrintGlobalLocation(&g2_loc, *g2); 859 Printf(" [1] size=%zd '%s' %s\n", g1->size, 860 MaybeDemangleGlobalName(g1->name), g1_loc.data()); 861 Printf(" [2] size=%zd '%s' %s\n", g2->size, 862 MaybeDemangleGlobalName(g2->name), g2_loc.data()); 863 if (stack_id1 && stack_id2) { 864 Printf("These globals were registered at these points:\n"); 865 Printf(" [1]:\n"); 866 StackDepotGet(stack_id1).Print(); 867 Printf(" [2]:\n"); 868 StackDepotGet(stack_id2).Print(); 869 } 870 Report("HINT: if you don't care about these warnings you may set " 871 "ASAN_OPTIONS=detect_odr_violation=0\n"); 872 InternalScopedString error_msg(256); 873 error_msg.append("odr-violation: global '%s' at %s", 874 MaybeDemangleGlobalName(g1->name), g1_loc.data()); 875 ReportErrorSummary(error_msg.data()); 876 } 877 878 // ----------------------- CheckForInvalidPointerPair ----------- {{{1 879 static NOINLINE void 880 ReportInvalidPointerPair(uptr pc, uptr bp, uptr sp, uptr a1, uptr a2) { 881 ScopedInErrorReport in_report; 882 Decorator d; 883 Printf("%s", d.Warning()); 884 Report("ERROR: AddressSanitizer: invalid-pointer-pair: %p %p\n", a1, a2); 885 Printf("%s", d.EndWarning()); 886 GET_STACK_TRACE_FATAL(pc, bp); 887 stack.Print(); 888 DescribeAddress(a1, 1); 889 DescribeAddress(a2, 1); 890 ReportErrorSummary("invalid-pointer-pair", &stack); 891 } 892 893 static INLINE void CheckForInvalidPointerPair(void *p1, void *p2) { 894 if (!flags()->detect_invalid_pointer_pairs) return; 895 uptr a1 = reinterpret_cast<uptr>(p1); 896 uptr a2 = reinterpret_cast<uptr>(p2); 897 AsanChunkView chunk1 = FindHeapChunkByAddress(a1); 898 AsanChunkView chunk2 = FindHeapChunkByAddress(a2); 899 bool valid1 = chunk1.IsValid(); 900 bool valid2 = chunk2.IsValid(); 901 if ((valid1 != valid2) || (valid1 && valid2 && !chunk1.Eq(chunk2))) { 902 GET_CALLER_PC_BP_SP; \ 903 return ReportInvalidPointerPair(pc, bp, sp, a1, a2); 904 } 905 } 906 // ----------------------- Mac-specific reports ----------------- {{{1 907 908 void WarnMacFreeUnallocated(uptr addr, uptr zone_ptr, const char *zone_name, 909 BufferedStackTrace *stack) { 910 // Just print a warning here. 911 Printf("free_common(%p) -- attempting to free unallocated memory.\n" 912 "AddressSanitizer is ignoring this error on Mac OS now.\n", 913 addr); 914 PrintZoneForPointer(addr, zone_ptr, zone_name); 915 stack->Print(); 916 DescribeHeapAddress(addr, 1); 917 } 918 919 void ReportMacMzReallocUnknown(uptr addr, uptr zone_ptr, const char *zone_name, 920 BufferedStackTrace *stack) { 921 ScopedInErrorReport in_report; 922 Printf("mz_realloc(%p) -- attempting to realloc unallocated memory.\n" 923 "This is an unrecoverable problem, exiting now.\n", 924 addr); 925 PrintZoneForPointer(addr, zone_ptr, zone_name); 926 stack->Print(); 927 DescribeHeapAddress(addr, 1); 928 } 929 930 void ReportMacCfReallocUnknown(uptr addr, uptr zone_ptr, const char *zone_name, 931 BufferedStackTrace *stack) { 932 ScopedInErrorReport in_report; 933 Printf("cf_realloc(%p) -- attempting to realloc unallocated memory.\n" 934 "This is an unrecoverable problem, exiting now.\n", 935 addr); 936 PrintZoneForPointer(addr, zone_ptr, zone_name); 937 stack->Print(); 938 DescribeHeapAddress(addr, 1); 939 } 940 941 } // namespace __asan 942 943 // --------------------------- Interface --------------------- {{{1 944 using namespace __asan; // NOLINT 945 946 void __asan_report_error(uptr pc, uptr bp, uptr sp, uptr addr, int is_write, 947 uptr access_size, u32 exp) { 948 ENABLE_FRAME_POINTER; 949 950 // Optimization experiments. 951 // The experiments can be used to evaluate potential optimizations that remove 952 // instrumentation (assess false negatives). Instead of completely removing 953 // some instrumentation, compiler can emit special calls into runtime 954 // (e.g. __asan_report_exp_load1 instead of __asan_report_load1) and pass 955 // mask of experiments (exp). 956 // The reaction to a non-zero value of exp is to be defined. 957 (void)exp; 958 959 // Determine the error type. 960 const char *bug_descr = "unknown-crash"; 961 if (AddrIsInMem(addr)) { 962 u8 *shadow_addr = (u8*)MemToShadow(addr); 963 // If we are accessing 16 bytes, look at the second shadow byte. 964 if (*shadow_addr == 0 && access_size > SHADOW_GRANULARITY) 965 shadow_addr++; 966 // If we are in the partial right redzone, look at the next shadow byte. 967 if (*shadow_addr > 0 && *shadow_addr < 128) 968 shadow_addr++; 969 switch (*shadow_addr) { 970 case kAsanHeapLeftRedzoneMagic: 971 case kAsanHeapRightRedzoneMagic: 972 case kAsanArrayCookieMagic: 973 bug_descr = "heap-buffer-overflow"; 974 break; 975 case kAsanHeapFreeMagic: 976 bug_descr = "heap-use-after-free"; 977 break; 978 case kAsanStackLeftRedzoneMagic: 979 bug_descr = "stack-buffer-underflow"; 980 break; 981 case kAsanInitializationOrderMagic: 982 bug_descr = "initialization-order-fiasco"; 983 break; 984 case kAsanStackMidRedzoneMagic: 985 case kAsanStackRightRedzoneMagic: 986 case kAsanStackPartialRedzoneMagic: 987 bug_descr = "stack-buffer-overflow"; 988 break; 989 case kAsanStackAfterReturnMagic: 990 bug_descr = "stack-use-after-return"; 991 break; 992 case kAsanUserPoisonedMemoryMagic: 993 bug_descr = "use-after-poison"; 994 break; 995 case kAsanContiguousContainerOOBMagic: 996 bug_descr = "container-overflow"; 997 break; 998 case kAsanStackUseAfterScopeMagic: 999 bug_descr = "stack-use-after-scope"; 1000 break; 1001 case kAsanGlobalRedzoneMagic: 1002 bug_descr = "global-buffer-overflow"; 1003 break; 1004 case kAsanIntraObjectRedzone: 1005 bug_descr = "intra-object-overflow"; 1006 break; 1007 case kAsanAllocaLeftMagic: 1008 case kAsanAllocaRightMagic: 1009 bug_descr = "dynamic-stack-buffer-overflow"; 1010 break; 1011 } 1012 } 1013 1014 ReportData report = { pc, sp, bp, addr, (bool)is_write, access_size, 1015 bug_descr }; 1016 ScopedInErrorReport in_report(&report); 1017 1018 Decorator d; 1019 Printf("%s", d.Warning()); 1020 Report("ERROR: AddressSanitizer: %s on address " 1021 "%p at pc %p bp %p sp %p\n", 1022 bug_descr, (void*)addr, pc, bp, sp); 1023 Printf("%s", d.EndWarning()); 1024 1025 u32 curr_tid = GetCurrentTidOrInvalid(); 1026 char tname[128]; 1027 Printf("%s%s of size %zu at %p thread T%d%s%s\n", 1028 d.Access(), 1029 access_size ? (is_write ? "WRITE" : "READ") : "ACCESS", 1030 access_size, (void*)addr, curr_tid, 1031 ThreadNameWithParenthesis(curr_tid, tname, sizeof(tname)), 1032 d.EndAccess()); 1033 1034 GET_STACK_TRACE_FATAL(pc, bp); 1035 stack.Print(); 1036 1037 DescribeAddress(addr, access_size); 1038 ReportErrorSummary(bug_descr, &stack); 1039 PrintShadowMemoryForAddress(addr); 1040 } 1041 1042 void NOINLINE __asan_set_error_report_callback(void (*callback)(const char*)) { 1043 error_report_callback = callback; 1044 if (callback) { 1045 error_message_buffer_size = 1 << 16; 1046 error_message_buffer = 1047 (char*)MmapOrDie(error_message_buffer_size, __func__); 1048 error_message_buffer_pos = 0; 1049 } 1050 } 1051 1052 void __asan_describe_address(uptr addr) { 1053 // Thread registry must be locked while we're describing an address. 1054 asanThreadRegistry().Lock(); 1055 DescribeAddress(addr, 1); 1056 asanThreadRegistry().Unlock(); 1057 } 1058 1059 int __asan_report_present() { 1060 return report_happened ? 1 : 0; 1061 } 1062 1063 uptr __asan_get_report_pc() { 1064 return report_data.pc; 1065 } 1066 1067 uptr __asan_get_report_bp() { 1068 return report_data.bp; 1069 } 1070 1071 uptr __asan_get_report_sp() { 1072 return report_data.sp; 1073 } 1074 1075 uptr __asan_get_report_address() { 1076 return report_data.addr; 1077 } 1078 1079 int __asan_get_report_access_type() { 1080 return report_data.is_write ? 1 : 0; 1081 } 1082 1083 uptr __asan_get_report_access_size() { 1084 return report_data.access_size; 1085 } 1086 1087 const char *__asan_get_report_description() { 1088 return report_data.description; 1089 } 1090 1091 extern "C" { 1092 SANITIZER_INTERFACE_ATTRIBUTE 1093 void __sanitizer_ptr_sub(void *a, void *b) { 1094 CheckForInvalidPointerPair(a, b); 1095 } 1096 SANITIZER_INTERFACE_ATTRIBUTE 1097 void __sanitizer_ptr_cmp(void *a, void *b) { 1098 CheckForInvalidPointerPair(a, b); 1099 } 1100 } // extern "C" 1101 1102 #if !SANITIZER_SUPPORTS_WEAK_HOOKS 1103 // Provide default implementation of __asan_on_error that does nothing 1104 // and may be overriden by user. 1105 SANITIZER_INTERFACE_ATTRIBUTE SANITIZER_WEAK_ATTRIBUTE NOINLINE 1106 void __asan_on_error() {} 1107 #endif 1108