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