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