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