1//===-- asan_descriptions.cpp -----------------------------------*- C++ -*-===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file is a part of AddressSanitizer, an address sanity checker.
10//
11// ASan functions for getting information about an address and/or printing it.
12//===----------------------------------------------------------------------===//
13
14#include "asan_descriptions.h"
15#include "asan_mapping.h"
16#include "asan_report.h"
17#include "asan_stack.h"
18#include "sanitizer_common/sanitizer_stackdepot.h"
19
20namespace __asan {
21
22AsanThreadIdAndName::AsanThreadIdAndName(AsanThreadContext *t) {
23 if (!t) {
24 internal_snprintf(buffer: name, length: sizeof(name), format: "T-1");
25 return;
26 }
27 int len = internal_snprintf(buffer: name, length: sizeof(name), format: "T%llu", t->unique_id);
28 CHECK(((unsigned int)len) < sizeof(name));
29 if (internal_strlen(s: t->name))
30 internal_snprintf(buffer: &name[len], length: sizeof(name) - len, format: " (%s)", t->name);
31}
32
33AsanThreadIdAndName::AsanThreadIdAndName(u32 tid)
34 : AsanThreadIdAndName(
35 tid == kInvalidTid ? nullptr : GetThreadContextByTidLocked(tid)) {
36 asanThreadRegistry().CheckLocked();
37}
38
39// Prints this thread and, if flags()->print_full_thread_history, its ancestors
40void DescribeThread(AsanThreadContext *context) {
41 while (true) {
42 CHECK(context);
43 asanThreadRegistry().CheckLocked();
44 // No need to announce the main thread.
45 if (context->tid == kMainTid || context->announced) {
46 return;
47 }
48 context->announced = true;
49
50 InternalScopedString str;
51 str.AppendF(format: "Thread %s", AsanThreadIdAndName(context).c_str());
52
53 AsanThreadContext* parent_context =
54 context->parent_tid == kInvalidTid
55 ? nullptr
56 : GetThreadContextByTidLocked(tid: context->parent_tid);
57
58 // `context->parent_tid` may point to reused slot. Check `unique_id` which
59 // is always smaller for the parent, always greater for a new user.
60 if (!parent_context || context->unique_id <= parent_context->unique_id) {
61 str.Append(str: " created by unknown thread\n");
62 Printf(format: "%s", str.data());
63 return;
64 }
65 str.AppendF(format: " created by %s here:\n",
66 AsanThreadIdAndName(context->parent_tid).c_str());
67 Printf(format: "%s", str.data());
68 StackDepotGet(id: context->stack_id).Print();
69
70 // Describe parent thread if requested
71 if (flags()->print_full_thread_history)
72 context = parent_context;
73 else
74 return;
75 }
76}
77
78// Shadow descriptions
79static bool GetShadowKind(uptr addr, ShadowKind *shadow_kind) {
80 CHECK(!AddrIsInMem(addr));
81 if (AddrIsInShadowGap(a: addr)) {
82 *shadow_kind = kShadowKindGap;
83 } else if (AddrIsInHighShadow(a: addr)) {
84 *shadow_kind = kShadowKindHigh;
85 } else if (AddrIsInLowShadow(a: addr)) {
86 *shadow_kind = kShadowKindLow;
87 } else {
88 return false;
89 }
90 return true;
91}
92
93bool DescribeAddressIfShadow(uptr addr) {
94 ShadowAddressDescription descr;
95 if (!GetShadowAddressInformation(addr, descr: &descr)) return false;
96 descr.Print();
97 return true;
98}
99
100bool GetShadowAddressInformation(uptr addr, ShadowAddressDescription *descr) {
101 if (AddrIsInMem(a: addr)) return false;
102 ShadowKind shadow_kind;
103 if (!GetShadowKind(addr, shadow_kind: &shadow_kind)) return false;
104 if (shadow_kind != kShadowKindGap) descr->shadow_byte = *(u8 *)addr;
105 descr->addr = addr;
106 descr->kind = shadow_kind;
107 return true;
108}
109
110// Heap descriptions
111static void GetAccessToHeapChunkInformation(ChunkAccess *descr,
112 AsanChunkView chunk, uptr addr,
113 uptr access_size) {
114 descr->bad_addr = addr;
115 if (chunk.AddrIsAtLeft(addr, access_size, offset: &descr->offset)) {
116 descr->access_type = kAccessTypeLeft;
117 } else if (chunk.AddrIsAtRight(addr, access_size, offset: &descr->offset)) {
118 descr->access_type = kAccessTypeRight;
119 if (descr->offset < 0) {
120 descr->bad_addr -= descr->offset;
121 descr->offset = 0;
122 }
123 } else if (chunk.AddrIsInside(addr, access_size, offset: &descr->offset)) {
124 descr->access_type = kAccessTypeInside;
125 } else {
126 descr->access_type = kAccessTypeUnknown;
127 }
128 descr->chunk_begin = chunk.Beg();
129 descr->chunk_size = chunk.UsedSize();
130 descr->user_requested_alignment = chunk.UserRequestedAlignment();
131 descr->alloc_type = chunk.GetAllocType();
132}
133
134static void PrintHeapChunkAccess(uptr addr, const ChunkAccess &descr) {
135 Decorator d;
136 InternalScopedString str;
137 str.Append(str: d.Location());
138 switch (descr.access_type) {
139 case kAccessTypeLeft:
140 str.AppendF(format: "%p is located %zd bytes before", (void *)descr.bad_addr,
141 descr.offset);
142 break;
143 case kAccessTypeRight:
144 str.AppendF(format: "%p is located %zd bytes after", (void *)descr.bad_addr,
145 descr.offset);
146 break;
147 case kAccessTypeInside:
148 str.AppendF(format: "%p is located %zd bytes inside of", (void *)descr.bad_addr,
149 descr.offset);
150 break;
151 case kAccessTypeUnknown:
152 str.AppendF(
153 format: "%p is located somewhere around (this is AddressSanitizer bug!)",
154 (void *)descr.bad_addr);
155 }
156 str.AppendF(format: " %zu-byte region [%p,%p)\n", descr.chunk_size,
157 (void *)descr.chunk_begin,
158 (void *)(descr.chunk_begin + descr.chunk_size));
159 str.Append(str: d.Default());
160 Printf(format: "%s", str.data());
161}
162
163bool GetHeapAddressInformation(uptr addr, uptr access_size,
164 HeapAddressDescription *descr) {
165 AsanChunkView chunk = FindHeapChunkByAddress(address: addr);
166 if (!chunk.IsValid()) {
167 return false;
168 }
169 descr->addr = addr;
170 GetAccessToHeapChunkInformation(descr: &descr->chunk_access, chunk, addr,
171 access_size);
172 CHECK_NE(chunk.AllocTid(), kInvalidTid);
173 descr->alloc_tid = chunk.AllocTid();
174 descr->alloc_stack_id = chunk.GetAllocStackId();
175 descr->free_tid = chunk.FreeTid();
176 if (descr->free_tid != kInvalidTid)
177 descr->free_stack_id = chunk.GetFreeStackId();
178 return true;
179}
180
181static StackTrace GetStackTraceFromId(u32 id) {
182 CHECK(id);
183 StackTrace res = StackDepotGet(id);
184 CHECK(res.trace);
185 return res;
186}
187
188bool DescribeAddressIfHeap(uptr addr, uptr access_size) {
189 HeapAddressDescription descr;
190 if (!GetHeapAddressInformation(addr, access_size, descr: &descr)) {
191 Printf(
192 format: "AddressSanitizer can not describe address in more detail "
193 "(wild memory access suspected).\n");
194 return false;
195 }
196 descr.Print();
197 return true;
198}
199
200// Stack descriptions
201bool GetStackAddressInformation(uptr addr, uptr access_size,
202 StackAddressDescription *descr) {
203 AsanThread *t = FindThreadByStackAddress(addr);
204 if (!t) return false;
205
206 descr->addr = addr;
207 descr->tid = t->tid();
208 // Try to fetch precise stack frame for this access.
209 AsanThread::StackFrameAccess access;
210 if (!t->GetStackFrameAccessByAddr(addr, access: &access)) {
211 descr->frame_descr = nullptr;
212 return true;
213 }
214
215 descr->offset = access.offset;
216 descr->access_size = access_size;
217 descr->frame_pc = access.frame_pc;
218 descr->frame_descr = access.frame_descr;
219
220#if SANITIZER_PPC64V1 || SANITIZER_AIX
221 // On PowerPC64 ELFv1 or AIX, the address of a function actually points to a
222 // three-doubleword (or three-word for 32-bit AIX) data structure with
223 // the first field containing the address of the function's code.
224 descr->frame_pc = *reinterpret_cast<uptr *>(descr->frame_pc);
225#endif
226 descr->frame_pc += 16;
227
228 return true;
229}
230
231static void PrintAccessAndVarIntersection(const StackVarDescr &var, uptr addr,
232 uptr access_size, uptr prev_var_end,
233 uptr next_var_beg) {
234 uptr var_end = var.beg + var.size;
235 uptr addr_end = addr + access_size;
236 const char *pos_descr = nullptr;
237 // If the variable [var.beg, var_end) is the nearest variable to the
238 // current memory access, indicate it in the log.
239 if (addr >= var.beg) {
240 if (addr_end <= var_end)
241 pos_descr = "is inside"; // May happen if this is a use-after-return.
242 else if (addr < var_end)
243 pos_descr = "partially overflows";
244 else if (addr_end <= next_var_beg &&
245 next_var_beg - addr_end >= addr - var_end)
246 pos_descr = "overflows";
247 } else {
248 if (addr_end > var.beg)
249 pos_descr = "partially underflows";
250 else if (addr >= prev_var_end && addr - prev_var_end >= var.beg - addr_end)
251 pos_descr = "underflows";
252 }
253 InternalScopedString str;
254 str.AppendF(format: " [%zd, %zd)", var.beg, var_end);
255 // Render variable name.
256 str.Append(str: " '");
257 for (uptr i = 0; i < var.name_len; ++i) {
258 str.AppendF(format: "%c", var.name_pos[i]);
259 }
260 str.Append(str: "'");
261 if (var.line > 0) {
262 str.AppendF(format: " (line %zd)", var.line);
263 }
264 if (pos_descr) {
265 Decorator d;
266 // FIXME: we may want to also print the size of the access here,
267 // but in case of accesses generated by memset it may be confusing.
268 str.AppendF(format: "%s <== Memory access at offset %zd %s this variable%s\n",
269 d.Location(), addr, pos_descr, d.Default());
270 } else {
271 str.Append(str: "\n");
272 }
273 Printf(format: "%s", str.data());
274}
275
276bool DescribeAddressIfStack(uptr addr, uptr access_size) {
277 StackAddressDescription descr;
278 if (!GetStackAddressInformation(addr, access_size, descr: &descr)) return false;
279 descr.Print();
280 return true;
281}
282
283// Global descriptions
284static void DescribeAddressRelativeToGlobal(uptr addr, uptr access_size,
285 const __asan_global &g) {
286 InternalScopedString str;
287 Decorator d;
288 str.Append(str: d.Location());
289 if (addr < g.beg) {
290 str.AppendF(format: "%p is located %zd bytes before", (void *)addr, g.beg - addr);
291 } else if (addr + access_size > g.beg + g.size) {
292 if (addr < g.beg + g.size) addr = g.beg + g.size;
293 str.AppendF(format: "%p is located %zd bytes after", (void *)addr,
294 addr - (g.beg + g.size));
295 } else {
296 // Can it happen?
297 str.AppendF(format: "%p is located %zd bytes inside of", (void *)addr,
298 addr - g.beg);
299 }
300 str.AppendF(format: " global variable '%s' defined in '",
301 MaybeDemangleGlobalName(name: g.name));
302 PrintGlobalLocation(str: &str, g, /*print_module_name=*/false);
303 str.AppendF(format: "' (%p) of size %zu\n", (void *)g.beg, g.size);
304 str.Append(str: d.Default());
305 PrintGlobalNameIfASCII(str: &str, g);
306 Printf(format: "%s", str.data());
307}
308
309bool GetGlobalAddressInformation(uptr addr, uptr access_size,
310 GlobalAddressDescription *descr) {
311 descr->addr = addr;
312 int globals_num = GetGlobalsForAddress(addr, globals: descr->globals, reg_sites: descr->reg_sites,
313 ARRAY_SIZE(descr->globals));
314 descr->size = globals_num;
315 descr->access_size = access_size;
316 return globals_num != 0;
317}
318
319bool DescribeAddressIfGlobal(uptr addr, uptr access_size,
320 const char *bug_type) {
321 GlobalAddressDescription descr;
322 if (!GetGlobalAddressInformation(addr, access_size, descr: &descr)) return false;
323
324 descr.Print(bug_type);
325 return true;
326}
327
328void ShadowAddressDescription::Print() const {
329 Printf(format: "Address %p is located in the %s area.\n", (void *)addr,
330 ShadowNames[kind]);
331}
332
333void GlobalAddressDescription::Print(const char *bug_type) const {
334 for (int i = 0; i < size; i++) {
335 DescribeAddressRelativeToGlobal(addr, access_size, g: globals[i]);
336 if (bug_type &&
337 0 == internal_strcmp(s1: bug_type, s2: "initialization-order-fiasco") &&
338 reg_sites[i]) {
339 Printf(format: " registered at:\n");
340 StackDepotGet(id: reg_sites[i]).Print();
341 }
342 }
343}
344
345bool GlobalAddressDescription::PointsInsideTheSameVariable(
346 const GlobalAddressDescription &other) const {
347 if (size == 0 || other.size == 0) return false;
348
349 for (uptr i = 0; i < size; i++) {
350 const __asan_global &a = globals[i];
351 for (uptr j = 0; j < other.size; j++) {
352 const __asan_global &b = other.globals[j];
353 if (a.beg == b.beg &&
354 a.beg <= addr &&
355 b.beg <= other.addr &&
356 (addr + access_size) < (a.beg + a.size) &&
357 (other.addr + other.access_size) < (b.beg + b.size))
358 return true;
359 }
360 }
361
362 return false;
363}
364
365void StackAddressDescription::Print() const {
366 Decorator d;
367 Printf(format: "%s", d.Location());
368 Printf(format: "Address %p is located in stack of thread %s", (void *)addr,
369 AsanThreadIdAndName(tid).c_str());
370
371 if (!frame_descr) {
372 Printf(format: "%s\n", d.Default());
373 return;
374 }
375 Printf(format: " at offset %zu in frame%s\n", offset, d.Default());
376
377 // Now we print the frame where the alloca has happened.
378 // We print this frame as a stack trace with one element.
379 // The symbolizer may print more than one frame if inlining was involved.
380 // The frame numbers may be different than those in the stack trace printed
381 // previously. That's unfortunate, but I have no better solution,
382 // especially given that the alloca may be from entirely different place
383 // (e.g. use-after-scope, or different thread's stack).
384 Printf(format: "%s", d.Default());
385 StackTrace alloca_stack(&frame_pc, 1);
386 alloca_stack.Print();
387
388 InternalMmapVector<StackVarDescr> vars;
389 vars.reserve(new_size: 16);
390 if (!ParseFrameDescription(frame_descr, vars: &vars)) {
391 Printf(
392 format: "AddressSanitizer can't parse the stack frame "
393 "descriptor: |%s|\n",
394 frame_descr);
395 // 'addr' is a stack address, so return true even if we can't parse frame
396 return;
397 }
398 uptr n_objects = vars.size();
399 // Report the number of stack objects.
400 Printf(format: " This frame has %zu object(s):\n", n_objects);
401
402 // Report all objects in this frame.
403 for (uptr i = 0; i < n_objects; i++) {
404 uptr prev_var_end = i ? vars[i - 1].beg + vars[i - 1].size : 0;
405 uptr next_var_beg = i + 1 < n_objects ? vars[i + 1].beg : ~(0UL);
406 PrintAccessAndVarIntersection(var: vars[i], addr: offset, access_size, prev_var_end,
407 next_var_beg);
408 }
409 Printf(
410 format: "HINT: this may be a false positive if your program uses "
411 "some custom stack unwind mechanism, swapcontext or vfork\n");
412 if (SANITIZER_WINDOWS)
413 Printf(format: " (longjmp, SEH and C++ exceptions *are* supported)\n");
414 else
415 Printf(format: " (longjmp and C++ exceptions *are* supported)\n");
416
417 DescribeThread(context: GetThreadContextByTidLocked(tid));
418}
419
420void HeapAddressDescription::Print() const {
421 PrintHeapChunkAccess(addr, descr: chunk_access);
422
423 asanThreadRegistry().CheckLocked();
424 AsanThreadContext *alloc_thread = GetThreadContextByTidLocked(tid: alloc_tid);
425 StackTrace alloc_stack = GetStackTraceFromId(id: alloc_stack_id);
426
427 Decorator d;
428 AsanThreadContext *free_thread = nullptr;
429 if (free_tid != kInvalidTid) {
430 free_thread = GetThreadContextByTidLocked(tid: free_tid);
431 Printf(format: "%sfreed by thread %s here:%s\n", d.Allocation(),
432 AsanThreadIdAndName(free_thread).c_str(), d.Default());
433 StackTrace free_stack = GetStackTraceFromId(id: free_stack_id);
434 free_stack.Print();
435 Printf(format: "%spreviously allocated by thread %s here:%s\n", d.Allocation(),
436 AsanThreadIdAndName(alloc_thread).c_str(), d.Default());
437 } else {
438 Printf(format: "%sallocated by thread %s here:%s\n", d.Allocation(),
439 AsanThreadIdAndName(alloc_thread).c_str(), d.Default());
440 }
441 alloc_stack.Print();
442 DescribeThread(t: GetCurrentThread());
443 if (free_thread) DescribeThread(context: free_thread);
444 DescribeThread(context: alloc_thread);
445}
446
447AddressDescription::AddressDescription(uptr addr, uptr access_size,
448 bool shouldLockThreadRegistry) {
449 if (GetShadowAddressInformation(addr, descr: &data.shadow)) {
450 data.kind = kAddressKindShadow;
451 return;
452 }
453
454 // Check global first. On AIX, some global data defined in shared libraries
455 // are put to the STACK region for unknown reasons. Check global first can
456 // workaround this issue.
457 // TODO: Look into whether there's a different solution to this problem.
458#if SANITIZER_AIX
459 if (GetGlobalAddressInformation(addr, access_size, &data.global)) {
460 data.kind = kAddressKindGlobal;
461 return;
462 }
463#endif
464
465 if (GetHeapAddressInformation(addr, access_size, descr: &data.heap)) {
466 data.kind = kAddressKindHeap;
467 return;
468 }
469
470 bool isStackMemory = false;
471 if (shouldLockThreadRegistry) {
472 ThreadRegistryLock l(&asanThreadRegistry());
473 isStackMemory = GetStackAddressInformation(addr, access_size, descr: &data.stack);
474 } else {
475 isStackMemory = GetStackAddressInformation(addr, access_size, descr: &data.stack);
476 }
477 if (isStackMemory) {
478 data.kind = kAddressKindStack;
479 return;
480 }
481
482// GetGlobalAddressInformation is called earlier on AIX due to a workaround
483#if !SANITIZER_AIX
484 if (GetGlobalAddressInformation(addr, access_size, descr: &data.global)) {
485 data.kind = kAddressKindGlobal;
486 return;
487 }
488#endif
489
490 data.kind = kAddressKindWild;
491 data.wild.addr = addr;
492 data.wild.access_size = access_size;
493}
494
495void WildAddressDescription::Print() const {
496 Printf(format: "Address %p is a wild pointer inside of access range of size %p.\n",
497 (void *)addr, (void *)access_size);
498}
499
500void PrintAddressDescription(uptr addr, uptr access_size,
501 const char *bug_type) {
502 ShadowAddressDescription shadow_descr;
503 if (GetShadowAddressInformation(addr, descr: &shadow_descr)) {
504 shadow_descr.Print();
505 return;
506 }
507
508 GlobalAddressDescription global_descr;
509 if (GetGlobalAddressInformation(addr, access_size, descr: &global_descr)) {
510 global_descr.Print(bug_type);
511 return;
512 }
513
514 StackAddressDescription stack_descr;
515 if (GetStackAddressInformation(addr, access_size, descr: &stack_descr)) {
516 stack_descr.Print();
517 return;
518 }
519
520 HeapAddressDescription heap_descr;
521 if (GetHeapAddressInformation(addr, access_size, descr: &heap_descr)) {
522 heap_descr.Print();
523 return;
524 }
525
526 // We exhausted our possibilities. Bail out.
527 Printf(
528 format: "AddressSanitizer can not describe address in more detail "
529 "(wild memory access suspected).\n");
530}
531} // namespace __asan
532