1//===-- asan_poisoning.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// Shadow memory poisoning by ASan RTL and by user application.
13//===----------------------------------------------------------------------===//
14
15#include "asan_poisoning.h"
16#include "asan_report.h"
17#include "asan_stack.h"
18#include "sanitizer_common/sanitizer_libc.h"
19#include "sanitizer_common/sanitizer_flags.h"
20
21namespace __asan {
22
23void PoisonShadow(uptr addr, uptr size, u8 value) {
24  if (!flags()->poison_heap) return;
25  CHECK(AddrIsAlignedByGranularity(addr));
26  CHECK(AddrIsInMem(addr));
27  CHECK(AddrIsAlignedByGranularity(addr + size));
28  CHECK(AddrIsInMem(addr + size - SHADOW_GRANULARITY));
29  CHECK(REAL(memset));
30  FastPoisonShadow(addr, size, value);
31}
32
33void PoisonShadowPartialRightRedzone(uptr addr,
34                                     uptr size,
35                                     uptr redzone_size,
36                                     u8 value) {
37  if (!flags()->poison_heap) return;
38  CHECK(AddrIsAlignedByGranularity(addr));
39  CHECK(AddrIsInMem(addr));
40  FastPoisonShadowPartialRightRedzone(addr, size, redzone_size, value);
41}
42
43struct ShadowSegmentEndpoint {
44  u8 *chunk;
45  s8 offset;  // in [0, SHADOW_GRANULARITY)
46  s8 value;  // = *chunk;
47
48  explicit ShadowSegmentEndpoint(uptr address) {
49    chunk = (u8*)MemToShadow(address);
50    offset = address & (SHADOW_GRANULARITY - 1);
51    value = *chunk;
52  }
53};
54
55void FlushUnneededASanShadowMemory(uptr p, uptr size) {
56    // Since asan's mapping is compacting, the shadow chunk may be
57    // not page-aligned, so we only flush the page-aligned portion.
58    uptr page_size = GetPageSizeCached();
59    uptr shadow_beg = RoundUpTo(MemToShadow(p), page_size);
60    uptr shadow_end = RoundDownTo(MemToShadow(p + size), page_size);
61    FlushUnneededShadowMemory(shadow_beg, shadow_end - shadow_beg);
62}
63
64}  // namespace __asan
65
66// ---------------------- Interface ---------------- {{{1
67using namespace __asan;  // NOLINT
68
69// Current implementation of __asan_(un)poison_memory_region doesn't check
70// that user program (un)poisons the memory it owns. It poisons memory
71// conservatively, and unpoisons progressively to make sure asan shadow
72// mapping invariant is preserved (see detailed mapping description here:
73// http://code.google.com/p/address-sanitizer/wiki/AddressSanitizerAlgorithm).
74//
75// * if user asks to poison region [left, right), the program poisons
76// at least [left, AlignDown(right)).
77// * if user asks to unpoison region [left, right), the program unpoisons
78// at most [AlignDown(left), right).
79void __asan_poison_memory_region(void const volatile *addr, uptr size) {
80  if (!flags()->allow_user_poisoning || size == 0) return;
81  uptr beg_addr = (uptr)addr;
82  uptr end_addr = beg_addr + size;
83  VPrintf(1, "Trying to poison memory region [%p, %p)\n", (void *)beg_addr,
84          (void *)end_addr);
85  ShadowSegmentEndpoint beg(beg_addr);
86  ShadowSegmentEndpoint end(end_addr);
87  if (beg.chunk == end.chunk) {
88    CHECK(beg.offset < end.offset);
89    s8 value = beg.value;
90    CHECK(value == end.value);
91    // We can only poison memory if the byte in end.offset is unaddressable.
92    // No need to re-poison memory if it is poisoned already.
93    if (value > 0 && value <= end.offset) {
94      if (beg.offset > 0) {
95        *beg.chunk = Min(value, beg.offset);
96      } else {
97        *beg.chunk = kAsanUserPoisonedMemoryMagic;
98      }
99    }
100    return;
101  }
102  CHECK(beg.chunk < end.chunk);
103  if (beg.offset > 0) {
104    // Mark bytes from beg.offset as unaddressable.
105    if (beg.value == 0) {
106      *beg.chunk = beg.offset;
107    } else {
108      *beg.chunk = Min(beg.value, beg.offset);
109    }
110    beg.chunk++;
111  }
112  REAL(memset)(beg.chunk, kAsanUserPoisonedMemoryMagic, end.chunk - beg.chunk);
113  // Poison if byte in end.offset is unaddressable.
114  if (end.value > 0 && end.value <= end.offset) {
115    *end.chunk = kAsanUserPoisonedMemoryMagic;
116  }
117}
118
119void __asan_unpoison_memory_region(void const volatile *addr, uptr size) {
120  if (!flags()->allow_user_poisoning || size == 0) return;
121  uptr beg_addr = (uptr)addr;
122  uptr end_addr = beg_addr + size;
123  VPrintf(1, "Trying to unpoison memory region [%p, %p)\n", (void *)beg_addr,
124          (void *)end_addr);
125  ShadowSegmentEndpoint beg(beg_addr);
126  ShadowSegmentEndpoint end(end_addr);
127  if (beg.chunk == end.chunk) {
128    CHECK(beg.offset < end.offset);
129    s8 value = beg.value;
130    CHECK(value == end.value);
131    // We unpoison memory bytes up to enbytes up to end.offset if it is not
132    // unpoisoned already.
133    if (value != 0) {
134      *beg.chunk = Max(value, end.offset);
135    }
136    return;
137  }
138  CHECK(beg.chunk < end.chunk);
139  if (beg.offset > 0) {
140    *beg.chunk = 0;
141    beg.chunk++;
142  }
143  REAL(memset)(beg.chunk, 0, end.chunk - beg.chunk);
144  if (end.offset > 0 && end.value != 0) {
145    *end.chunk = Max(end.value, end.offset);
146  }
147}
148
149int __asan_address_is_poisoned(void const volatile *addr) {
150  return __asan::AddressIsPoisoned((uptr)addr);
151}
152
153uptr __asan_region_is_poisoned(uptr beg, uptr size) {
154  if (!size) return 0;
155  uptr end = beg + size;
156  if (!AddrIsInMem(beg)) return beg;
157  if (!AddrIsInMem(end)) return end;
158  CHECK_LT(beg, end);
159  uptr aligned_b = RoundUpTo(beg, SHADOW_GRANULARITY);
160  uptr aligned_e = RoundDownTo(end, SHADOW_GRANULARITY);
161  uptr shadow_beg = MemToShadow(aligned_b);
162  uptr shadow_end = MemToShadow(aligned_e);
163  // First check the first and the last application bytes,
164  // then check the SHADOW_GRANULARITY-aligned region by calling
165  // mem_is_zero on the corresponding shadow.
166  if (!__asan::AddressIsPoisoned(beg) &&
167      !__asan::AddressIsPoisoned(end - 1) &&
168      (shadow_end <= shadow_beg ||
169       __sanitizer::mem_is_zero((const char *)shadow_beg,
170                                shadow_end - shadow_beg)))
171    return 0;
172  // The fast check failed, so we have a poisoned byte somewhere.
173  // Find it slowly.
174  for (; beg < end; beg++)
175    if (__asan::AddressIsPoisoned(beg))
176      return beg;
177  UNREACHABLE("mem_is_zero returned false, but poisoned byte was not found");
178  return 0;
179}
180
181#define CHECK_SMALL_REGION(p, size, isWrite)                  \
182  do {                                                        \
183    uptr __p = reinterpret_cast<uptr>(p);                     \
184    uptr __size = size;                                       \
185    if (UNLIKELY(__asan::AddressIsPoisoned(__p) ||            \
186        __asan::AddressIsPoisoned(__p + __size - 1))) {       \
187      GET_CURRENT_PC_BP_SP;                                   \
188      uptr __bad = __asan_region_is_poisoned(__p, __size);    \
189      __asan_report_error(pc, bp, sp, __bad, isWrite, __size);\
190    }                                                         \
191  } while (false);                                            \
192
193
194extern "C" SANITIZER_INTERFACE_ATTRIBUTE
195u16 __sanitizer_unaligned_load16(const uu16 *p) {
196  CHECK_SMALL_REGION(p, sizeof(*p), false);
197  return *p;
198}
199
200extern "C" SANITIZER_INTERFACE_ATTRIBUTE
201u32 __sanitizer_unaligned_load32(const uu32 *p) {
202  CHECK_SMALL_REGION(p, sizeof(*p), false);
203  return *p;
204}
205
206extern "C" SANITIZER_INTERFACE_ATTRIBUTE
207u64 __sanitizer_unaligned_load64(const uu64 *p) {
208  CHECK_SMALL_REGION(p, sizeof(*p), false);
209  return *p;
210}
211
212extern "C" SANITIZER_INTERFACE_ATTRIBUTE
213void __sanitizer_unaligned_store16(uu16 *p, u16 x) {
214  CHECK_SMALL_REGION(p, sizeof(*p), true);
215  *p = x;
216}
217
218extern "C" SANITIZER_INTERFACE_ATTRIBUTE
219void __sanitizer_unaligned_store32(uu32 *p, u32 x) {
220  CHECK_SMALL_REGION(p, sizeof(*p), true);
221  *p = x;
222}
223
224extern "C" SANITIZER_INTERFACE_ATTRIBUTE
225void __sanitizer_unaligned_store64(uu64 *p, u64 x) {
226  CHECK_SMALL_REGION(p, sizeof(*p), true);
227  *p = x;
228}
229
230// This is a simplified version of __asan_(un)poison_memory_region, which
231// assumes that left border of region to be poisoned is properly aligned.
232static void PoisonAlignedStackMemory(uptr addr, uptr size, bool do_poison) {
233  if (size == 0) return;
234  uptr aligned_size = size & ~(SHADOW_GRANULARITY - 1);
235  PoisonShadow(addr, aligned_size,
236               do_poison ? kAsanStackUseAfterScopeMagic : 0);
237  if (size == aligned_size)
238    return;
239  s8 end_offset = (s8)(size - aligned_size);
240  s8* shadow_end = (s8*)MemToShadow(addr + aligned_size);
241  s8 end_value = *shadow_end;
242  if (do_poison) {
243    // If possible, mark all the bytes mapping to last shadow byte as
244    // unaddressable.
245    if (end_value > 0 && end_value <= end_offset)
246      *shadow_end = (s8)kAsanStackUseAfterScopeMagic;
247  } else {
248    // If necessary, mark few first bytes mapping to last shadow byte
249    // as addressable
250    if (end_value != 0)
251      *shadow_end = Max(end_value, end_offset);
252  }
253}
254
255void __asan_poison_stack_memory(uptr addr, uptr size) {
256  VReport(1, "poisoning: %p %zx\n", (void *)addr, size);
257  PoisonAlignedStackMemory(addr, size, true);
258}
259
260void __asan_unpoison_stack_memory(uptr addr, uptr size) {
261  VReport(1, "unpoisoning: %p %zx\n", (void *)addr, size);
262  PoisonAlignedStackMemory(addr, size, false);
263}
264
265void __sanitizer_annotate_contiguous_container(const void *beg_p,
266                                               const void *end_p,
267                                               const void *old_mid_p,
268                                               const void *new_mid_p) {
269  if (!flags()->detect_container_overflow) return;
270  VPrintf(2, "contiguous_container: %p %p %p %p\n", beg_p, end_p, old_mid_p,
271          new_mid_p);
272  uptr beg = reinterpret_cast<uptr>(beg_p);
273  uptr end = reinterpret_cast<uptr>(end_p);
274  uptr old_mid = reinterpret_cast<uptr>(old_mid_p);
275  uptr new_mid = reinterpret_cast<uptr>(new_mid_p);
276  uptr granularity = SHADOW_GRANULARITY;
277  if (!(beg <= old_mid && beg <= new_mid && old_mid <= end && new_mid <= end &&
278        IsAligned(beg, granularity))) {
279    GET_STACK_TRACE_FATAL_HERE;
280    ReportBadParamsToAnnotateContiguousContainer(beg, end, old_mid, new_mid,
281                                                 &stack);
282  }
283  CHECK_LE(end - beg,
284           FIRST_32_SECOND_64(1UL << 30, 1UL << 34)); // Sanity check.
285
286  uptr a = RoundDownTo(Min(old_mid, new_mid), granularity);
287  uptr c = RoundUpTo(Max(old_mid, new_mid), granularity);
288  uptr d1 = RoundDownTo(old_mid, granularity);
289  // uptr d2 = RoundUpTo(old_mid, granularity);
290  // Currently we should be in this state:
291  // [a, d1) is good, [d2, c) is bad, [d1, d2) is partially good.
292  // Make a quick sanity check that we are indeed in this state.
293  //
294  // FIXME: Two of these three checks are disabled until we fix
295  // https://code.google.com/p/address-sanitizer/issues/detail?id=258.
296  // if (d1 != d2)
297  //  CHECK_EQ(*(u8*)MemToShadow(d1), old_mid - d1);
298  if (a + granularity <= d1)
299    CHECK_EQ(*(u8*)MemToShadow(a), 0);
300  // if (d2 + granularity <= c && c <= end)
301  //   CHECK_EQ(*(u8 *)MemToShadow(c - granularity),
302  //            kAsanContiguousContainerOOBMagic);
303
304  uptr b1 = RoundDownTo(new_mid, granularity);
305  uptr b2 = RoundUpTo(new_mid, granularity);
306  // New state:
307  // [a, b1) is good, [b2, c) is bad, [b1, b2) is partially good.
308  PoisonShadow(a, b1 - a, 0);
309  PoisonShadow(b2, c - b2, kAsanContiguousContainerOOBMagic);
310  if (b1 != b2) {
311    CHECK_EQ(b2 - b1, granularity);
312    *(u8*)MemToShadow(b1) = static_cast<u8>(new_mid - b1);
313  }
314}
315
316int __sanitizer_verify_contiguous_container(const void *beg_p,
317                                            const void *mid_p,
318                                            const void *end_p) {
319  if (!flags()->detect_container_overflow) return 1;
320  uptr beg = reinterpret_cast<uptr>(beg_p);
321  uptr end = reinterpret_cast<uptr>(end_p);
322  uptr mid = reinterpret_cast<uptr>(mid_p);
323  CHECK_LE(beg, mid);
324  CHECK_LE(mid, end);
325  // Check some bytes starting from beg, some bytes around mid, and some bytes
326  // ending with end.
327  uptr kMaxRangeToCheck = 32;
328  uptr r1_beg = beg;
329  uptr r1_end = Min(end + kMaxRangeToCheck, mid);
330  uptr r2_beg = Max(beg, mid - kMaxRangeToCheck);
331  uptr r2_end = Min(end, mid + kMaxRangeToCheck);
332  uptr r3_beg = Max(end - kMaxRangeToCheck, mid);
333  uptr r3_end = end;
334  for (uptr i = r1_beg; i < r1_end; i++)
335    if (AddressIsPoisoned(i))
336      return 0;
337  for (uptr i = r2_beg; i < mid; i++)
338    if (AddressIsPoisoned(i))
339      return 0;
340  for (uptr i = mid; i < r2_end; i++)
341    if (!AddressIsPoisoned(i))
342      return 0;
343  for (uptr i = r3_beg; i < r3_end; i++)
344    if (!AddressIsPoisoned(i))
345      return 0;
346  return 1;
347}
348// --- Implementation of LSan-specific functions --- {{{1
349namespace __lsan {
350bool WordIsPoisoned(uptr addr) {
351  return (__asan_region_is_poisoned(addr, sizeof(uptr)) != 0);
352}
353}
354
355