1 //===-- asan_poisoning.cpp ------------------------------------------------===//
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 // Shadow memory poisoning by ASan RTL and by user application.
12 //===----------------------------------------------------------------------===//
13 
14 #include "asan_poisoning.h"
15 #include "asan_report.h"
16 #include "asan_stack.h"
17 #include "sanitizer_common/sanitizer_atomic.h"
18 #include "sanitizer_common/sanitizer_libc.h"
19 #include "sanitizer_common/sanitizer_flags.h"
20 
21 namespace __asan {
22 
23 static atomic_uint8_t can_poison_memory;
24 
25 void SetCanPoisonMemory(bool value) {
26   atomic_store(&can_poison_memory, value, memory_order_release);
27 }
28 
29 bool CanPoisonMemory() {
30   return atomic_load(&can_poison_memory, memory_order_acquire);
31 }
32 
33 void PoisonShadow(uptr addr, uptr size, u8 value) {
34   if (value && !CanPoisonMemory()) return;
35   CHECK(AddrIsAlignedByGranularity(addr));
36   CHECK(AddrIsInMem(addr));
37   CHECK(AddrIsAlignedByGranularity(addr + size));
38   CHECK(AddrIsInMem(addr + size - SHADOW_GRANULARITY));
39   CHECK(REAL(memset));
40   FastPoisonShadow(addr, size, value);
41 }
42 
43 void PoisonShadowPartialRightRedzone(uptr addr,
44                                      uptr size,
45                                      uptr redzone_size,
46                                      u8 value) {
47   if (!CanPoisonMemory()) return;
48   CHECK(AddrIsAlignedByGranularity(addr));
49   CHECK(AddrIsInMem(addr));
50   FastPoisonShadowPartialRightRedzone(addr, size, redzone_size, value);
51 }
52 
53 struct ShadowSegmentEndpoint {
54   u8 *chunk;
55   s8 offset;  // in [0, SHADOW_GRANULARITY)
56   s8 value;  // = *chunk;
57 
58   explicit ShadowSegmentEndpoint(uptr address) {
59     chunk = (u8*)MemToShadow(address);
60     offset = address & (SHADOW_GRANULARITY - 1);
61     value = *chunk;
62   }
63 };
64 
65 void FlushUnneededASanShadowMemory(uptr p, uptr size) {
66   // Since asan's mapping is compacting, the shadow chunk may be
67   // not page-aligned, so we only flush the page-aligned portion.
68   ReleaseMemoryPagesToOS(MemToShadow(p), MemToShadow(p + size));
69 }
70 
71 void AsanPoisonOrUnpoisonIntraObjectRedzone(uptr ptr, uptr size, bool poison) {
72   uptr end = ptr + size;
73   if (Verbosity()) {
74     Printf("__asan_%spoison_intra_object_redzone [%p,%p) %zd\n",
75            poison ? "" : "un", ptr, end, size);
76     if (Verbosity() >= 2)
77       PRINT_CURRENT_STACK();
78   }
79   CHECK(size);
80   CHECK_LE(size, 4096);
81   CHECK(IsAligned(end, SHADOW_GRANULARITY));
82   if (!IsAligned(ptr, SHADOW_GRANULARITY)) {
83     *(u8 *)MemToShadow(ptr) =
84         poison ? static_cast<u8>(ptr % SHADOW_GRANULARITY) : 0;
85     ptr |= SHADOW_GRANULARITY - 1;
86     ptr++;
87   }
88   for (; ptr < end; ptr += SHADOW_GRANULARITY)
89     *(u8*)MemToShadow(ptr) = poison ? kAsanIntraObjectRedzone : 0;
90 }
91 
92 }  // namespace __asan
93 
94 // ---------------------- Interface ---------------- {{{1
95 using namespace __asan;
96 
97 // Current implementation of __asan_(un)poison_memory_region doesn't check
98 // that user program (un)poisons the memory it owns. It poisons memory
99 // conservatively, and unpoisons progressively to make sure asan shadow
100 // mapping invariant is preserved (see detailed mapping description here:
101 // https://github.com/google/sanitizers/wiki/AddressSanitizerAlgorithm).
102 //
103 // * if user asks to poison region [left, right), the program poisons
104 // at least [left, AlignDown(right)).
105 // * if user asks to unpoison region [left, right), the program unpoisons
106 // at most [AlignDown(left), right).
107 void __asan_poison_memory_region(void const volatile *addr, uptr size) {
108   if (!flags()->allow_user_poisoning || size == 0) return;
109   uptr beg_addr = (uptr)addr;
110   uptr end_addr = beg_addr + size;
111   VPrintf(3, "Trying to poison memory region [%p, %p)\n", (void *)beg_addr,
112           (void *)end_addr);
113   ShadowSegmentEndpoint beg(beg_addr);
114   ShadowSegmentEndpoint end(end_addr);
115   if (beg.chunk == end.chunk) {
116     CHECK_LT(beg.offset, end.offset);
117     s8 value = beg.value;
118     CHECK_EQ(value, end.value);
119     // We can only poison memory if the byte in end.offset is unaddressable.
120     // No need to re-poison memory if it is poisoned already.
121     if (value > 0 && value <= end.offset) {
122       if (beg.offset > 0) {
123         *beg.chunk = Min(value, beg.offset);
124       } else {
125         *beg.chunk = kAsanUserPoisonedMemoryMagic;
126       }
127     }
128     return;
129   }
130   CHECK_LT(beg.chunk, end.chunk);
131   if (beg.offset > 0) {
132     // Mark bytes from beg.offset as unaddressable.
133     if (beg.value == 0) {
134       *beg.chunk = beg.offset;
135     } else {
136       *beg.chunk = Min(beg.value, beg.offset);
137     }
138     beg.chunk++;
139   }
140   REAL(memset)(beg.chunk, kAsanUserPoisonedMemoryMagic, end.chunk - beg.chunk);
141   // Poison if byte in end.offset is unaddressable.
142   if (end.value > 0 && end.value <= end.offset) {
143     *end.chunk = kAsanUserPoisonedMemoryMagic;
144   }
145 }
146 
147 void __asan_unpoison_memory_region(void const volatile *addr, uptr size) {
148   if (!flags()->allow_user_poisoning || size == 0) return;
149   uptr beg_addr = (uptr)addr;
150   uptr end_addr = beg_addr + size;
151   VPrintf(3, "Trying to unpoison memory region [%p, %p)\n", (void *)beg_addr,
152           (void *)end_addr);
153   ShadowSegmentEndpoint beg(beg_addr);
154   ShadowSegmentEndpoint end(end_addr);
155   if (beg.chunk == end.chunk) {
156     CHECK_LT(beg.offset, end.offset);
157     s8 value = beg.value;
158     CHECK_EQ(value, end.value);
159     // We unpoison memory bytes up to enbytes up to end.offset if it is not
160     // unpoisoned already.
161     if (value != 0) {
162       *beg.chunk = Max(value, end.offset);
163     }
164     return;
165   }
166   CHECK_LT(beg.chunk, end.chunk);
167   if (beg.offset > 0) {
168     *beg.chunk = 0;
169     beg.chunk++;
170   }
171   REAL(memset)(beg.chunk, 0, end.chunk - beg.chunk);
172   if (end.offset > 0 && end.value != 0) {
173     *end.chunk = Max(end.value, end.offset);
174   }
175 }
176 
177 int __asan_address_is_poisoned(void const volatile *addr) {
178   return __asan::AddressIsPoisoned((uptr)addr);
179 }
180 
181 uptr __asan_region_is_poisoned(uptr beg, uptr size) {
182   if (!size) return 0;
183   uptr end = beg + size;
184   if (SANITIZER_MYRIAD2) {
185     // On Myriad, address not in DRAM range need to be treated as
186     // unpoisoned.
187     if (!AddrIsInMem(beg) && !AddrIsInShadow(beg)) return 0;
188     if (!AddrIsInMem(end) && !AddrIsInShadow(end)) return 0;
189   } else {
190     if (!AddrIsInMem(beg)) return beg;
191     if (!AddrIsInMem(end)) return end;
192   }
193   CHECK_LT(beg, end);
194   uptr aligned_b = RoundUpTo(beg, SHADOW_GRANULARITY);
195   uptr aligned_e = RoundDownTo(end, SHADOW_GRANULARITY);
196   uptr shadow_beg = MemToShadow(aligned_b);
197   uptr shadow_end = MemToShadow(aligned_e);
198   // First check the first and the last application bytes,
199   // then check the SHADOW_GRANULARITY-aligned region by calling
200   // mem_is_zero on the corresponding shadow.
201   if (!__asan::AddressIsPoisoned(beg) &&
202       !__asan::AddressIsPoisoned(end - 1) &&
203       (shadow_end <= shadow_beg ||
204        __sanitizer::mem_is_zero((const char *)shadow_beg,
205                                 shadow_end - shadow_beg)))
206     return 0;
207   // The fast check failed, so we have a poisoned byte somewhere.
208   // Find it slowly.
209   for (; beg < end; beg++)
210     if (__asan::AddressIsPoisoned(beg))
211       return beg;
212   UNREACHABLE("mem_is_zero returned false, but poisoned byte was not found");
213   return 0;
214 }
215 
216 #define CHECK_SMALL_REGION(p, size, isWrite)                  \
217   do {                                                        \
218     uptr __p = reinterpret_cast<uptr>(p);                     \
219     uptr __size = size;                                       \
220     if (UNLIKELY(__asan::AddressIsPoisoned(__p) ||            \
221         __asan::AddressIsPoisoned(__p + __size - 1))) {       \
222       GET_CURRENT_PC_BP_SP;                                   \
223       uptr __bad = __asan_region_is_poisoned(__p, __size);    \
224       __asan_report_error(pc, bp, sp, __bad, isWrite, __size, 0);\
225     }                                                         \
226   } while (false)
227 
228 
229 extern "C" SANITIZER_INTERFACE_ATTRIBUTE
230 u16 __sanitizer_unaligned_load16(const uu16 *p) {
231   CHECK_SMALL_REGION(p, sizeof(*p), false);
232   return *p;
233 }
234 
235 extern "C" SANITIZER_INTERFACE_ATTRIBUTE
236 u32 __sanitizer_unaligned_load32(const uu32 *p) {
237   CHECK_SMALL_REGION(p, sizeof(*p), false);
238   return *p;
239 }
240 
241 extern "C" SANITIZER_INTERFACE_ATTRIBUTE
242 u64 __sanitizer_unaligned_load64(const uu64 *p) {
243   CHECK_SMALL_REGION(p, sizeof(*p), false);
244   return *p;
245 }
246 
247 extern "C" SANITIZER_INTERFACE_ATTRIBUTE
248 void __sanitizer_unaligned_store16(uu16 *p, u16 x) {
249   CHECK_SMALL_REGION(p, sizeof(*p), true);
250   *p = x;
251 }
252 
253 extern "C" SANITIZER_INTERFACE_ATTRIBUTE
254 void __sanitizer_unaligned_store32(uu32 *p, u32 x) {
255   CHECK_SMALL_REGION(p, sizeof(*p), true);
256   *p = x;
257 }
258 
259 extern "C" SANITIZER_INTERFACE_ATTRIBUTE
260 void __sanitizer_unaligned_store64(uu64 *p, u64 x) {
261   CHECK_SMALL_REGION(p, sizeof(*p), true);
262   *p = x;
263 }
264 
265 extern "C" SANITIZER_INTERFACE_ATTRIBUTE
266 void __asan_poison_cxx_array_cookie(uptr p) {
267   if (SANITIZER_WORDSIZE != 64) return;
268   if (!flags()->poison_array_cookie) return;
269   uptr s = MEM_TO_SHADOW(p);
270   *reinterpret_cast<u8*>(s) = kAsanArrayCookieMagic;
271 }
272 
273 extern "C" SANITIZER_INTERFACE_ATTRIBUTE
274 uptr __asan_load_cxx_array_cookie(uptr *p) {
275   if (SANITIZER_WORDSIZE != 64) return *p;
276   if (!flags()->poison_array_cookie) return *p;
277   uptr s = MEM_TO_SHADOW(reinterpret_cast<uptr>(p));
278   u8 sval = *reinterpret_cast<u8*>(s);
279   if (sval == kAsanArrayCookieMagic) return *p;
280   // If sval is not kAsanArrayCookieMagic it can only be freed memory,
281   // which means that we are going to get double-free. So, return 0 to avoid
282   // infinite loop of destructors. We don't want to report a double-free here
283   // though, so print a warning just in case.
284   // CHECK_EQ(sval, kAsanHeapFreeMagic);
285   if (sval == kAsanHeapFreeMagic) {
286     Report("AddressSanitizer: loaded array cookie from free-d memory; "
287            "expect a double-free report\n");
288     return 0;
289   }
290   // The cookie may remain unpoisoned if e.g. it comes from a custom
291   // operator new defined inside a class.
292   return *p;
293 }
294 
295 // This is a simplified version of __asan_(un)poison_memory_region, which
296 // assumes that left border of region to be poisoned is properly aligned.
297 static void PoisonAlignedStackMemory(uptr addr, uptr size, bool do_poison) {
298   if (size == 0) return;
299   uptr aligned_size = size & ~(SHADOW_GRANULARITY - 1);
300   PoisonShadow(addr, aligned_size,
301                do_poison ? kAsanStackUseAfterScopeMagic : 0);
302   if (size == aligned_size)
303     return;
304   s8 end_offset = (s8)(size - aligned_size);
305   s8* shadow_end = (s8*)MemToShadow(addr + aligned_size);
306   s8 end_value = *shadow_end;
307   if (do_poison) {
308     // If possible, mark all the bytes mapping to last shadow byte as
309     // unaddressable.
310     if (end_value > 0 && end_value <= end_offset)
311       *shadow_end = (s8)kAsanStackUseAfterScopeMagic;
312   } else {
313     // If necessary, mark few first bytes mapping to last shadow byte
314     // as addressable
315     if (end_value != 0)
316       *shadow_end = Max(end_value, end_offset);
317   }
318 }
319 
320 void __asan_set_shadow_00(uptr addr, uptr size) {
321   REAL(memset)((void *)addr, 0, size);
322 }
323 
324 void __asan_set_shadow_f1(uptr addr, uptr size) {
325   REAL(memset)((void *)addr, 0xf1, size);
326 }
327 
328 void __asan_set_shadow_f2(uptr addr, uptr size) {
329   REAL(memset)((void *)addr, 0xf2, size);
330 }
331 
332 void __asan_set_shadow_f3(uptr addr, uptr size) {
333   REAL(memset)((void *)addr, 0xf3, size);
334 }
335 
336 void __asan_set_shadow_f5(uptr addr, uptr size) {
337   REAL(memset)((void *)addr, 0xf5, size);
338 }
339 
340 void __asan_set_shadow_f8(uptr addr, uptr size) {
341   REAL(memset)((void *)addr, 0xf8, size);
342 }
343 
344 void __asan_poison_stack_memory(uptr addr, uptr size) {
345   VReport(1, "poisoning: %p %zx\n", (void *)addr, size);
346   PoisonAlignedStackMemory(addr, size, true);
347 }
348 
349 void __asan_unpoison_stack_memory(uptr addr, uptr size) {
350   VReport(1, "unpoisoning: %p %zx\n", (void *)addr, size);
351   PoisonAlignedStackMemory(addr, size, false);
352 }
353 
354 void __sanitizer_annotate_contiguous_container(const void *beg_p,
355                                                const void *end_p,
356                                                const void *old_mid_p,
357                                                const void *new_mid_p) {
358   if (!flags()->detect_container_overflow) return;
359   VPrintf(2, "contiguous_container: %p %p %p %p\n", beg_p, end_p, old_mid_p,
360           new_mid_p);
361   uptr beg = reinterpret_cast<uptr>(beg_p);
362   uptr end = reinterpret_cast<uptr>(end_p);
363   uptr old_mid = reinterpret_cast<uptr>(old_mid_p);
364   uptr new_mid = reinterpret_cast<uptr>(new_mid_p);
365   uptr granularity = SHADOW_GRANULARITY;
366   if (!(beg <= old_mid && beg <= new_mid && old_mid <= end && new_mid <= end &&
367         IsAligned(beg, granularity))) {
368     GET_STACK_TRACE_FATAL_HERE;
369     ReportBadParamsToAnnotateContiguousContainer(beg, end, old_mid, new_mid,
370                                                  &stack);
371   }
372   CHECK_LE(end - beg,
373            FIRST_32_SECOND_64(1UL << 30, 1ULL << 34)); // Sanity check.
374 
375   uptr a = RoundDownTo(Min(old_mid, new_mid), granularity);
376   uptr c = RoundUpTo(Max(old_mid, new_mid), granularity);
377   uptr d1 = RoundDownTo(old_mid, granularity);
378   // uptr d2 = RoundUpTo(old_mid, granularity);
379   // Currently we should be in this state:
380   // [a, d1) is good, [d2, c) is bad, [d1, d2) is partially good.
381   // Make a quick sanity check that we are indeed in this state.
382   //
383   // FIXME: Two of these three checks are disabled until we fix
384   // https://github.com/google/sanitizers/issues/258.
385   // if (d1 != d2)
386   //  CHECK_EQ(*(u8*)MemToShadow(d1), old_mid - d1);
387   if (a + granularity <= d1)
388     CHECK_EQ(*(u8*)MemToShadow(a), 0);
389   // if (d2 + granularity <= c && c <= end)
390   //   CHECK_EQ(*(u8 *)MemToShadow(c - granularity),
391   //            kAsanContiguousContainerOOBMagic);
392 
393   uptr b1 = RoundDownTo(new_mid, granularity);
394   uptr b2 = RoundUpTo(new_mid, granularity);
395   // New state:
396   // [a, b1) is good, [b2, c) is bad, [b1, b2) is partially good.
397   PoisonShadow(a, b1 - a, 0);
398   PoisonShadow(b2, c - b2, kAsanContiguousContainerOOBMagic);
399   if (b1 != b2) {
400     CHECK_EQ(b2 - b1, granularity);
401     *(u8*)MemToShadow(b1) = static_cast<u8>(new_mid - b1);
402   }
403 }
404 
405 const void *__sanitizer_contiguous_container_find_bad_address(
406     const void *beg_p, const void *mid_p, const void *end_p) {
407   if (!flags()->detect_container_overflow)
408     return nullptr;
409   uptr beg = reinterpret_cast<uptr>(beg_p);
410   uptr end = reinterpret_cast<uptr>(end_p);
411   uptr mid = reinterpret_cast<uptr>(mid_p);
412   CHECK_LE(beg, mid);
413   CHECK_LE(mid, end);
414   // Check some bytes starting from beg, some bytes around mid, and some bytes
415   // ending with end.
416   uptr kMaxRangeToCheck = 32;
417   uptr r1_beg = beg;
418   uptr r1_end = Min(beg + kMaxRangeToCheck, mid);
419   uptr r2_beg = Max(beg, mid - kMaxRangeToCheck);
420   uptr r2_end = Min(end, mid + kMaxRangeToCheck);
421   uptr r3_beg = Max(end - kMaxRangeToCheck, mid);
422   uptr r3_end = end;
423   for (uptr i = r1_beg; i < r1_end; i++)
424     if (AddressIsPoisoned(i))
425       return reinterpret_cast<const void *>(i);
426   for (uptr i = r2_beg; i < mid; i++)
427     if (AddressIsPoisoned(i))
428       return reinterpret_cast<const void *>(i);
429   for (uptr i = mid; i < r2_end; i++)
430     if (!AddressIsPoisoned(i))
431       return reinterpret_cast<const void *>(i);
432   for (uptr i = r3_beg; i < r3_end; i++)
433     if (!AddressIsPoisoned(i))
434       return reinterpret_cast<const void *>(i);
435   return nullptr;
436 }
437 
438 int __sanitizer_verify_contiguous_container(const void *beg_p,
439                                             const void *mid_p,
440                                             const void *end_p) {
441   return __sanitizer_contiguous_container_find_bad_address(beg_p, mid_p,
442                                                            end_p) == nullptr;
443 }
444 
445 extern "C" SANITIZER_INTERFACE_ATTRIBUTE
446 void __asan_poison_intra_object_redzone(uptr ptr, uptr size) {
447   AsanPoisonOrUnpoisonIntraObjectRedzone(ptr, size, true);
448 }
449 
450 extern "C" SANITIZER_INTERFACE_ATTRIBUTE
451 void __asan_unpoison_intra_object_redzone(uptr ptr, uptr size) {
452   AsanPoisonOrUnpoisonIntraObjectRedzone(ptr, size, false);
453 }
454 
455 // --- Implementation of LSan-specific functions --- {{{1
456 namespace __lsan {
457 bool WordIsPoisoned(uptr addr) {
458   return (__asan_region_is_poisoned(addr, sizeof(uptr)) != 0);
459 }
460 }
461