xref: /llvm-project/compiler-rt/lib/asan/asan_poisoning.cpp (revision c76045d9bf3bd1c7a381dc85d1db63a38fd69aa4)
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 
16 #include "asan_report.h"
17 #include "asan_stack.h"
18 #include "sanitizer_common/sanitizer_atomic.h"
19 #include "sanitizer_common/sanitizer_common.h"
20 #include "sanitizer_common/sanitizer_flags.h"
21 #include "sanitizer_common/sanitizer_interface_internal.h"
22 #include "sanitizer_common/sanitizer_libc.h"
23 
24 namespace __asan {
25 
26 static atomic_uint8_t can_poison_memory;
27 
28 void SetCanPoisonMemory(bool value) {
29   atomic_store(&can_poison_memory, value, memory_order_release);
30 }
31 
32 bool CanPoisonMemory() {
33   return atomic_load(&can_poison_memory, memory_order_acquire);
34 }
35 
36 void PoisonShadow(uptr addr, uptr size, u8 value) {
37   if (value && !CanPoisonMemory()) return;
38   CHECK(AddrIsAlignedByGranularity(addr));
39   CHECK(AddrIsInMem(addr));
40   CHECK(AddrIsAlignedByGranularity(addr + size));
41   CHECK(AddrIsInMem(addr + size - ASAN_SHADOW_GRANULARITY));
42   CHECK(REAL(memset));
43   FastPoisonShadow(addr, size, value);
44 }
45 
46 void PoisonShadowPartialRightRedzone(uptr addr,
47                                      uptr size,
48                                      uptr redzone_size,
49                                      u8 value) {
50   if (!CanPoisonMemory()) return;
51   CHECK(AddrIsAlignedByGranularity(addr));
52   CHECK(AddrIsInMem(addr));
53   FastPoisonShadowPartialRightRedzone(addr, size, redzone_size, value);
54 }
55 
56 struct ShadowSegmentEndpoint {
57   u8 *chunk;
58   s8 offset;  // in [0, ASAN_SHADOW_GRANULARITY)
59   s8 value;  // = *chunk;
60 
61   explicit ShadowSegmentEndpoint(uptr address) {
62     chunk = (u8*)MemToShadow(address);
63     offset = address & (ASAN_SHADOW_GRANULARITY - 1);
64     value = *chunk;
65   }
66 };
67 
68 void AsanPoisonOrUnpoisonIntraObjectRedzone(uptr ptr, uptr size, bool poison) {
69   uptr end = ptr + size;
70   if (Verbosity()) {
71     Printf("__asan_%spoison_intra_object_redzone [%p,%p) %zd\n",
72            poison ? "" : "un", (void *)ptr, (void *)end, size);
73     if (Verbosity() >= 2)
74       PRINT_CURRENT_STACK();
75   }
76   CHECK(size);
77   CHECK_LE(size, 4096);
78   CHECK(IsAligned(end, ASAN_SHADOW_GRANULARITY));
79   if (!IsAligned(ptr, ASAN_SHADOW_GRANULARITY)) {
80     *(u8 *)MemToShadow(ptr) =
81         poison ? static_cast<u8>(ptr % ASAN_SHADOW_GRANULARITY) : 0;
82     ptr |= ASAN_SHADOW_GRANULARITY - 1;
83     ptr++;
84   }
85   for (; ptr < end; ptr += ASAN_SHADOW_GRANULARITY)
86     *(u8*)MemToShadow(ptr) = poison ? kAsanIntraObjectRedzone : 0;
87 }
88 
89 }  // namespace __asan
90 
91 // ---------------------- Interface ---------------- {{{1
92 using namespace __asan;
93 
94 // Current implementation of __asan_(un)poison_memory_region doesn't check
95 // that user program (un)poisons the memory it owns. It poisons memory
96 // conservatively, and unpoisons progressively to make sure asan shadow
97 // mapping invariant is preserved (see detailed mapping description here:
98 // https://github.com/google/sanitizers/wiki/AddressSanitizerAlgorithm).
99 //
100 // * if user asks to poison region [left, right), the program poisons
101 // at least [left, AlignDown(right)).
102 // * if user asks to unpoison region [left, right), the program unpoisons
103 // at most [AlignDown(left), right).
104 void __asan_poison_memory_region(void const volatile *addr, uptr size) {
105   if (!flags()->allow_user_poisoning || size == 0) return;
106   uptr beg_addr = (uptr)addr;
107   uptr end_addr = beg_addr + size;
108   VPrintf(3, "Trying to poison memory region [%p, %p)\n", (void *)beg_addr,
109           (void *)end_addr);
110   ShadowSegmentEndpoint beg(beg_addr);
111   ShadowSegmentEndpoint end(end_addr);
112   if (beg.chunk == end.chunk) {
113     CHECK_LT(beg.offset, end.offset);
114     s8 value = beg.value;
115     CHECK_EQ(value, end.value);
116     // We can only poison memory if the byte in end.offset is unaddressable.
117     // No need to re-poison memory if it is poisoned already.
118     if (value > 0 && value <= end.offset) {
119       if (beg.offset > 0) {
120         *beg.chunk = Min(value, beg.offset);
121       } else {
122         *beg.chunk = kAsanUserPoisonedMemoryMagic;
123       }
124     }
125     return;
126   }
127   CHECK_LT(beg.chunk, end.chunk);
128   if (beg.offset > 0) {
129     // Mark bytes from beg.offset as unaddressable.
130     if (beg.value == 0) {
131       *beg.chunk = beg.offset;
132     } else {
133       *beg.chunk = Min(beg.value, beg.offset);
134     }
135     beg.chunk++;
136   }
137   REAL(memset)(beg.chunk, kAsanUserPoisonedMemoryMagic, end.chunk - beg.chunk);
138   // Poison if byte in end.offset is unaddressable.
139   if (end.value > 0 && end.value <= end.offset) {
140     *end.chunk = kAsanUserPoisonedMemoryMagic;
141   }
142 }
143 
144 void __asan_unpoison_memory_region(void const volatile *addr, uptr size) {
145   if (!flags()->allow_user_poisoning || size == 0) return;
146   uptr beg_addr = (uptr)addr;
147   uptr end_addr = beg_addr + size;
148   VPrintf(3, "Trying to unpoison memory region [%p, %p)\n", (void *)beg_addr,
149           (void *)end_addr);
150   ShadowSegmentEndpoint beg(beg_addr);
151   ShadowSegmentEndpoint end(end_addr);
152   if (beg.chunk == end.chunk) {
153     CHECK_LT(beg.offset, end.offset);
154     s8 value = beg.value;
155     CHECK_EQ(value, end.value);
156     // We unpoison memory bytes up to enbytes up to end.offset if it is not
157     // unpoisoned already.
158     if (value != 0) {
159       *beg.chunk = Max(value, end.offset);
160     }
161     return;
162   }
163   CHECK_LT(beg.chunk, end.chunk);
164   REAL(memset)(beg.chunk, 0, end.chunk - beg.chunk);
165   if (end.offset > 0 && end.value != 0) {
166     *end.chunk = Max(end.value, end.offset);
167   }
168 }
169 
170 int __asan_address_is_poisoned(void const volatile *addr) {
171   return __asan::AddressIsPoisoned((uptr)addr);
172 }
173 
174 uptr __asan_region_is_poisoned(uptr beg, uptr size) {
175   if (!size)
176     return 0;
177   uptr end = beg + size;
178   if (!AddrIsInMem(beg))
179     return beg;
180   if (!AddrIsInMem(end))
181     return end;
182   CHECK_LT(beg, end);
183   uptr aligned_b = RoundUpTo(beg, ASAN_SHADOW_GRANULARITY);
184   uptr aligned_e = RoundDownTo(end, ASAN_SHADOW_GRANULARITY);
185   uptr shadow_beg = MemToShadow(aligned_b);
186   uptr shadow_end = MemToShadow(aligned_e);
187   // First check the first and the last application bytes,
188   // then check the ASAN_SHADOW_GRANULARITY-aligned region by calling
189   // mem_is_zero on the corresponding shadow.
190   if (!__asan::AddressIsPoisoned(beg) && !__asan::AddressIsPoisoned(end - 1) &&
191       (shadow_end <= shadow_beg ||
192        __sanitizer::mem_is_zero((const char *)shadow_beg,
193                                 shadow_end - shadow_beg)))
194     return 0;
195   // The fast check failed, so we have a poisoned byte somewhere.
196   // Find it slowly.
197   for (; beg < end; beg++)
198     if (__asan::AddressIsPoisoned(beg))
199       return beg;
200   UNREACHABLE("mem_is_zero returned false, but poisoned byte was not found");
201   return 0;
202 }
203 
204 #define CHECK_SMALL_REGION(p, size, isWrite)                  \
205   do {                                                        \
206     uptr __p = reinterpret_cast<uptr>(p);                     \
207     uptr __size = size;                                       \
208     if (UNLIKELY(__asan::AddressIsPoisoned(__p) ||            \
209         __asan::AddressIsPoisoned(__p + __size - 1))) {       \
210       GET_CURRENT_PC_BP_SP;                                   \
211       uptr __bad = __asan_region_is_poisoned(__p, __size);    \
212       __asan_report_error(pc, bp, sp, __bad, isWrite, __size, 0);\
213     }                                                         \
214   } while (false)
215 
216 
217 extern "C" SANITIZER_INTERFACE_ATTRIBUTE
218 u16 __sanitizer_unaligned_load16(const uu16 *p) {
219   CHECK_SMALL_REGION(p, sizeof(*p), false);
220   return *p;
221 }
222 
223 extern "C" SANITIZER_INTERFACE_ATTRIBUTE
224 u32 __sanitizer_unaligned_load32(const uu32 *p) {
225   CHECK_SMALL_REGION(p, sizeof(*p), false);
226   return *p;
227 }
228 
229 extern "C" SANITIZER_INTERFACE_ATTRIBUTE
230 u64 __sanitizer_unaligned_load64(const uu64 *p) {
231   CHECK_SMALL_REGION(p, sizeof(*p), false);
232   return *p;
233 }
234 
235 extern "C" SANITIZER_INTERFACE_ATTRIBUTE
236 void __sanitizer_unaligned_store16(uu16 *p, u16 x) {
237   CHECK_SMALL_REGION(p, sizeof(*p), true);
238   *p = x;
239 }
240 
241 extern "C" SANITIZER_INTERFACE_ATTRIBUTE
242 void __sanitizer_unaligned_store32(uu32 *p, u32 x) {
243   CHECK_SMALL_REGION(p, sizeof(*p), true);
244   *p = x;
245 }
246 
247 extern "C" SANITIZER_INTERFACE_ATTRIBUTE
248 void __sanitizer_unaligned_store64(uu64 *p, u64 x) {
249   CHECK_SMALL_REGION(p, sizeof(*p), true);
250   *p = x;
251 }
252 
253 extern "C" SANITIZER_INTERFACE_ATTRIBUTE
254 void __asan_poison_cxx_array_cookie(uptr p) {
255   if (SANITIZER_WORDSIZE != 64) return;
256   if (!flags()->poison_array_cookie) return;
257   uptr s = MEM_TO_SHADOW(p);
258   *reinterpret_cast<u8*>(s) = kAsanArrayCookieMagic;
259 }
260 
261 extern "C" SANITIZER_INTERFACE_ATTRIBUTE
262 uptr __asan_load_cxx_array_cookie(uptr *p) {
263   if (SANITIZER_WORDSIZE != 64) return *p;
264   if (!flags()->poison_array_cookie) return *p;
265   uptr s = MEM_TO_SHADOW(reinterpret_cast<uptr>(p));
266   u8 sval = *reinterpret_cast<u8*>(s);
267   if (sval == kAsanArrayCookieMagic) return *p;
268   // If sval is not kAsanArrayCookieMagic it can only be freed memory,
269   // which means that we are going to get double-free. So, return 0 to avoid
270   // infinite loop of destructors. We don't want to report a double-free here
271   // though, so print a warning just in case.
272   // CHECK_EQ(sval, kAsanHeapFreeMagic);
273   if (sval == kAsanHeapFreeMagic) {
274     Report("AddressSanitizer: loaded array cookie from free-d memory; "
275            "expect a double-free report\n");
276     return 0;
277   }
278   // The cookie may remain unpoisoned if e.g. it comes from a custom
279   // operator new defined inside a class.
280   return *p;
281 }
282 
283 // This is a simplified version of __asan_(un)poison_memory_region, which
284 // assumes that left border of region to be poisoned is properly aligned.
285 static void PoisonAlignedStackMemory(uptr addr, uptr size, bool do_poison) {
286   if (size == 0) return;
287   uptr aligned_size = size & ~(ASAN_SHADOW_GRANULARITY - 1);
288   PoisonShadow(addr, aligned_size,
289                do_poison ? kAsanStackUseAfterScopeMagic : 0);
290   if (size == aligned_size)
291     return;
292   s8 end_offset = (s8)(size - aligned_size);
293   s8* shadow_end = (s8*)MemToShadow(addr + aligned_size);
294   s8 end_value = *shadow_end;
295   if (do_poison) {
296     // If possible, mark all the bytes mapping to last shadow byte as
297     // unaddressable.
298     if (end_value > 0 && end_value <= end_offset)
299       *shadow_end = (s8)kAsanStackUseAfterScopeMagic;
300   } else {
301     // If necessary, mark few first bytes mapping to last shadow byte
302     // as addressable
303     if (end_value != 0)
304       *shadow_end = Max(end_value, end_offset);
305   }
306 }
307 
308 void __asan_set_shadow_00(uptr addr, uptr size) {
309   REAL(memset)((void *)addr, 0, size);
310 }
311 
312 void __asan_set_shadow_01(uptr addr, uptr size) {
313   REAL(memset)((void *)addr, 0x01, size);
314 }
315 
316 void __asan_set_shadow_02(uptr addr, uptr size) {
317   REAL(memset)((void *)addr, 0x02, size);
318 }
319 
320 void __asan_set_shadow_03(uptr addr, uptr size) {
321   REAL(memset)((void *)addr, 0x03, size);
322 }
323 
324 void __asan_set_shadow_04(uptr addr, uptr size) {
325   REAL(memset)((void *)addr, 0x04, size);
326 }
327 
328 void __asan_set_shadow_05(uptr addr, uptr size) {
329   REAL(memset)((void *)addr, 0x05, size);
330 }
331 
332 void __asan_set_shadow_06(uptr addr, uptr size) {
333   REAL(memset)((void *)addr, 0x06, size);
334 }
335 
336 void __asan_set_shadow_07(uptr addr, uptr size) {
337   REAL(memset)((void *)addr, 0x07, size);
338 }
339 
340 void __asan_set_shadow_f1(uptr addr, uptr size) {
341   REAL(memset)((void *)addr, 0xf1, size);
342 }
343 
344 void __asan_set_shadow_f2(uptr addr, uptr size) {
345   REAL(memset)((void *)addr, 0xf2, size);
346 }
347 
348 void __asan_set_shadow_f3(uptr addr, uptr size) {
349   REAL(memset)((void *)addr, 0xf3, size);
350 }
351 
352 void __asan_set_shadow_f5(uptr addr, uptr size) {
353   REAL(memset)((void *)addr, 0xf5, size);
354 }
355 
356 void __asan_set_shadow_f8(uptr addr, uptr size) {
357   REAL(memset)((void *)addr, 0xf8, size);
358 }
359 
360 void __asan_poison_stack_memory(uptr addr, uptr size) {
361   VReport(1, "poisoning: %p %zx\n", (void *)addr, size);
362   PoisonAlignedStackMemory(addr, size, true);
363 }
364 
365 void __asan_unpoison_stack_memory(uptr addr, uptr size) {
366   VReport(1, "unpoisoning: %p %zx\n", (void *)addr, size);
367   PoisonAlignedStackMemory(addr, size, false);
368 }
369 
370 static void FixUnalignedStorage(uptr storage_beg, uptr storage_end,
371                                 uptr &old_beg, uptr &old_end, uptr &new_beg,
372                                 uptr &new_end) {
373   constexpr uptr granularity = ASAN_SHADOW_GRANULARITY;
374   if (UNLIKELY(!AddrIsAlignedByGranularity(storage_end))) {
375     uptr end_down = RoundDownTo(storage_end, granularity);
376     // Ignore the last unaligned granule if the storage is followed by
377     // unpoisoned byte, because we can't poison the prefix anyway. Don't call
378     // AddressIsPoisoned at all if container changes does not affect the last
379     // granule at all.
380     if ((((old_end != new_end) && Max(old_end, new_end) > end_down) ||
381          ((old_beg != new_beg) && Max(old_beg, new_beg) > end_down)) &&
382         !AddressIsPoisoned(storage_end)) {
383       old_beg = Min(end_down, old_beg);
384       old_end = Min(end_down, old_end);
385       new_beg = Min(end_down, new_beg);
386       new_end = Min(end_down, new_end);
387     }
388   }
389 
390   // Handle misaligned begin and cut it off.
391   if (UNLIKELY(!AddrIsAlignedByGranularity(storage_beg))) {
392     uptr beg_up = RoundUpTo(storage_beg, granularity);
393     // The first unaligned granule needs special handling only if we had bytes
394     // there before and will have none after.
395     if ((new_beg == new_end || new_beg >= beg_up) && old_beg != old_end &&
396         old_beg < beg_up) {
397       // Keep granule prefix outside of the storage unpoisoned.
398       uptr beg_down = RoundDownTo(storage_beg, granularity);
399       *(u8 *)MemToShadow(beg_down) = storage_beg - beg_down;
400       old_beg = Max(beg_up, old_beg);
401       old_end = Max(beg_up, old_end);
402       new_beg = Max(beg_up, new_beg);
403       new_end = Max(beg_up, new_end);
404     }
405   }
406 }
407 
408 void __sanitizer_annotate_contiguous_container(const void *beg_p,
409                                                const void *end_p,
410                                                const void *old_mid_p,
411                                                const void *new_mid_p) {
412   if (!flags()->detect_container_overflow)
413     return;
414   VPrintf(3, "contiguous_container: %p %p %p %p\n", beg_p, end_p, old_mid_p,
415           new_mid_p);
416   uptr storage_beg = reinterpret_cast<uptr>(beg_p);
417   uptr storage_end = reinterpret_cast<uptr>(end_p);
418   uptr old_end = reinterpret_cast<uptr>(old_mid_p);
419   uptr new_end = reinterpret_cast<uptr>(new_mid_p);
420   uptr old_beg = storage_beg;
421   uptr new_beg = storage_beg;
422   uptr granularity = ASAN_SHADOW_GRANULARITY;
423   if (!(storage_beg <= old_end && storage_beg <= new_end &&
424         old_end <= storage_end && new_end <= storage_end)) {
425     GET_STACK_TRACE_FATAL_HERE;
426     ReportBadParamsToAnnotateContiguousContainer(storage_beg, storage_end,
427                                                  old_end, new_end, &stack);
428   }
429   CHECK_LE(storage_end - storage_beg,
430            FIRST_32_SECOND_64(1UL << 30, 1ULL << 40));  // Sanity check.
431 
432   if (old_end == new_end)
433     return;  // Nothing to do here.
434 
435   FixUnalignedStorage(storage_beg, storage_end, old_beg, old_end, new_beg,
436                       new_end);
437 
438   uptr a = RoundDownTo(Min(old_end, new_end), granularity);
439   uptr c = RoundUpTo(Max(old_end, new_end), granularity);
440   uptr d1 = RoundDownTo(old_end, granularity);
441   // uptr d2 = RoundUpTo(old_mid, granularity);
442   // Currently we should be in this state:
443   // [a, d1) is good, [d2, c) is bad, [d1, d2) is partially good.
444   // Make a quick sanity check that we are indeed in this state.
445   //
446   // FIXME: Two of these three checks are disabled until we fix
447   // https://github.com/google/sanitizers/issues/258.
448   // if (d1 != d2)
449   //  DCHECK_EQ(*(u8*)MemToShadow(d1), old_mid - d1);
450   //
451   // NOTE: curly brackets for the "if" below to silence a MSVC warning.
452   if (a + granularity <= d1) {
453     DCHECK_EQ(*(u8 *)MemToShadow(a), 0);
454   }
455   // if (d2 + granularity <= c && c <= end)
456   //   DCHECK_EQ(*(u8 *)MemToShadow(c - granularity),
457   //            kAsanContiguousContainerOOBMagic);
458 
459   uptr b1 = RoundDownTo(new_end, granularity);
460   uptr b2 = RoundUpTo(new_end, granularity);
461   // New state:
462   // [a, b1) is good, [b2, c) is bad, [b1, b2) is partially good.
463   if (b1 > a)
464     PoisonShadow(a, b1 - a, 0);
465   else if (c > b2)
466     PoisonShadow(b2, c - b2, kAsanContiguousContainerOOBMagic);
467   if (b1 != b2) {
468     CHECK_EQ(b2 - b1, granularity);
469     *(u8 *)MemToShadow(b1) = static_cast<u8>(new_end - b1);
470   }
471 }
472 
473 // Annotates a double ended contiguous memory area like std::deque's chunk.
474 // It allows detecting buggy accesses to allocated but not used begining
475 // or end items of such a container.
476 void __sanitizer_annotate_double_ended_contiguous_container(
477     const void *storage_beg_p, const void *storage_end_p,
478     const void *old_container_beg_p, const void *old_container_end_p,
479     const void *new_container_beg_p, const void *new_container_end_p) {
480   if (!flags()->detect_container_overflow)
481     return;
482 
483   VPrintf(3, "contiguous_container: %p %p %p %p %p %p\n", storage_beg_p,
484           storage_end_p, old_container_beg_p, old_container_end_p,
485           new_container_beg_p, new_container_end_p);
486 
487   uptr storage_beg = reinterpret_cast<uptr>(storage_beg_p);
488   uptr storage_end = reinterpret_cast<uptr>(storage_end_p);
489   uptr old_beg = reinterpret_cast<uptr>(old_container_beg_p);
490   uptr old_end = reinterpret_cast<uptr>(old_container_end_p);
491   uptr new_beg = reinterpret_cast<uptr>(new_container_beg_p);
492   uptr new_end = reinterpret_cast<uptr>(new_container_end_p);
493 
494   constexpr uptr granularity = ASAN_SHADOW_GRANULARITY;
495 
496   if (!(old_beg <= old_end && new_beg <= new_end) ||
497       !(storage_beg <= new_beg && new_end <= storage_end) ||
498       !(storage_beg <= old_beg && old_end <= storage_end)) {
499     GET_STACK_TRACE_FATAL_HERE;
500     ReportBadParamsToAnnotateDoubleEndedContiguousContainer(
501         storage_beg, storage_end, old_beg, old_end, new_beg, new_end, &stack);
502   }
503   CHECK_LE(storage_end - storage_beg,
504            FIRST_32_SECOND_64(1UL << 30, 1ULL << 40));  // Sanity check.
505 
506   if ((old_beg == old_end && new_beg == new_end) ||
507       (old_beg == new_beg && old_end == new_end))
508     return;  // Nothing to do here.
509 
510   FixUnalignedStorage(storage_beg, storage_end, old_beg, old_end, new_beg,
511                       new_end);
512 
513   // Handle non-intersecting new/old containers separately have simpler
514   // intersecting case.
515   if (old_beg == old_end || new_beg == new_end || new_end <= old_beg ||
516       old_end <= new_beg) {
517     if (old_beg != old_end) {
518       // Poisoning the old container.
519       uptr a = RoundDownTo(old_beg, granularity);
520       uptr b = RoundUpTo(old_end, granularity);
521       PoisonShadow(a, b - a, kAsanContiguousContainerOOBMagic);
522     }
523 
524     if (new_beg != new_end) {
525       // Unpoisoning the new container.
526       uptr a = RoundDownTo(new_beg, granularity);
527       uptr b = RoundDownTo(new_end, granularity);
528       PoisonShadow(a, b - a, 0);
529       if (!AddrIsAlignedByGranularity(new_end))
530         *(u8 *)MemToShadow(b) = static_cast<u8>(new_end - b);
531     }
532 
533     return;
534   }
535 
536   // Intersection of old and new containers is not empty.
537   CHECK_LT(new_beg, old_end);
538   CHECK_GT(new_end, old_beg);
539 
540   if (new_beg < old_beg) {
541     // Round down because we can't poison prefixes.
542     uptr a = RoundDownTo(new_beg, granularity);
543     // Round down and ignore the [c, old_beg) as its state defined by unchanged
544     // [old_beg, old_end).
545     uptr c = RoundDownTo(old_beg, granularity);
546     PoisonShadow(a, c - a, 0);
547   } else if (new_beg > old_beg) {
548     // Round down and poison [a, old_beg) because it was unpoisoned only as a
549     // prefix.
550     uptr a = RoundDownTo(old_beg, granularity);
551     // Round down and ignore the [c, new_beg) as its state defined by unchanged
552     // [new_beg, old_end).
553     uptr c = RoundDownTo(new_beg, granularity);
554 
555     PoisonShadow(a, c - a, kAsanContiguousContainerOOBMagic);
556   }
557 
558   if (new_end > old_end) {
559     // Round down to poison the prefix.
560     uptr a = RoundDownTo(old_end, granularity);
561     // Round down and handle remainder below.
562     uptr c = RoundDownTo(new_end, granularity);
563     PoisonShadow(a, c - a, 0);
564     if (!AddrIsAlignedByGranularity(new_end))
565       *(u8 *)MemToShadow(c) = static_cast<u8>(new_end - c);
566   } else if (new_end < old_end) {
567     // Round up and handle remained below.
568     uptr a2 = RoundUpTo(new_end, granularity);
569     // Round up to poison entire granule as we had nothing in [old_end, c2).
570     uptr c2 = RoundUpTo(old_end, granularity);
571     PoisonShadow(a2, c2 - a2, kAsanContiguousContainerOOBMagic);
572 
573     if (!AddrIsAlignedByGranularity(new_end)) {
574       uptr a = RoundDownTo(new_end, granularity);
575       *(u8 *)MemToShadow(a) = static_cast<u8>(new_end - a);
576     }
577   }
578 }
579 
580 // Marks the specified number of bytes in a granule as accessible or
581 // poisones the whole granule with kAsanContiguousContainerOOBMagic value.
582 static void SetContainerGranule(uptr ptr, u8 n) {
583   constexpr uptr granularity = ASAN_SHADOW_GRANULARITY;
584   u8 s = (n == granularity) ? 0 : (n ? n : kAsanContiguousContainerOOBMagic);
585   *(u8 *)MemToShadow(ptr) = s;
586 }
587 
588 // Performs a byte-by-byte copy of ASan annotations (shadow memory values).
589 // Result may be different due to ASan limitations, but result cannot lead
590 // to false positives (more memory than requested may get unpoisoned).
591 static void SlowCopyContainerAnnotations(uptr src_beg, uptr src_end,
592                                          uptr dst_beg, uptr dst_end) {
593   constexpr uptr granularity = ASAN_SHADOW_GRANULARITY;
594   uptr dst_end_down = RoundDownTo(dst_end, granularity);
595   uptr src_ptr = src_beg;
596   uptr dst_ptr = dst_beg;
597 
598   while (dst_ptr < dst_end) {
599     uptr granule_beg = RoundDownTo(dst_ptr, granularity);
600     uptr granule_end = granule_beg + granularity;
601     uptr unpoisoned_bytes = 0;
602 
603     uptr end = Min(granule_end, dst_end);
604     for (; dst_ptr != end; ++dst_ptr, ++src_ptr)
605       if (!AddressIsPoisoned(src_ptr))
606         unpoisoned_bytes = dst_ptr - granule_beg + 1;
607 
608     if (dst_ptr == dst_end && dst_end != dst_end_down &&
609         !AddressIsPoisoned(dst_end))
610       continue;
611 
612     if (unpoisoned_bytes != 0 || granule_beg >= dst_beg)
613       SetContainerGranule(granule_beg, unpoisoned_bytes);
614     else if (!AddressIsPoisoned(dst_beg))
615       SetContainerGranule(granule_beg, dst_beg - granule_beg);
616   }
617 }
618 
619 // Performs a byte-by-byte copy of ASan annotations (shadow memory values),
620 // going through bytes in reversed order, but not reversing annotations.
621 // Result may be different due to ASan limitations, but result cannot lead
622 // to false positives (more memory than requested may get unpoisoned).
623 static void SlowReversedCopyContainerAnnotations(uptr src_beg, uptr src_end,
624                                                  uptr dst_beg, uptr dst_end) {
625   constexpr uptr granularity = ASAN_SHADOW_GRANULARITY;
626   uptr dst_end_down = RoundDownTo(dst_end, granularity);
627   uptr src_ptr = src_end;
628   uptr dst_ptr = dst_end;
629 
630   while (dst_ptr > dst_beg) {
631     uptr granule_beg = RoundDownTo(dst_ptr - 1, granularity);
632     uptr unpoisoned_bytes = 0;
633 
634     uptr end = Max(granule_beg, dst_beg);
635     for (; dst_ptr != end; --dst_ptr, --src_ptr)
636       if (unpoisoned_bytes == 0 && !AddressIsPoisoned(src_ptr - 1))
637         unpoisoned_bytes = dst_ptr - granule_beg;
638 
639     if (dst_ptr >= dst_end_down && !AddressIsPoisoned(dst_end))
640       continue;
641 
642     if (granule_beg == dst_ptr || unpoisoned_bytes != 0)
643       SetContainerGranule(granule_beg, unpoisoned_bytes);
644     else if (!AddressIsPoisoned(dst_beg))
645       SetContainerGranule(granule_beg, dst_beg - granule_beg);
646   }
647 }
648 
649 // A helper function for __sanitizer_copy_contiguous_container_annotations,
650 // has assumption about begin and end of the container.
651 // Should not be used stand alone.
652 static void CopyContainerFirstGranuleAnnotation(uptr src_beg, uptr dst_beg) {
653   constexpr uptr granularity = ASAN_SHADOW_GRANULARITY;
654   // First granule
655   uptr src_beg_down = RoundDownTo(src_beg, granularity);
656   uptr dst_beg_down = RoundDownTo(dst_beg, granularity);
657   if (dst_beg_down == dst_beg)
658     return;
659   if (!AddressIsPoisoned(src_beg))
660     *(u8 *)MemToShadow(dst_beg_down) = *(u8 *)MemToShadow(src_beg_down);
661   else if (!AddressIsPoisoned(dst_beg))
662     SetContainerGranule(dst_beg_down, dst_beg - dst_beg_down);
663 }
664 
665 // A helper function for __sanitizer_copy_contiguous_container_annotations,
666 // has assumption about begin and end of the container.
667 // Should not be used stand alone.
668 static void CopyContainerLastGranuleAnnotation(uptr src_end, uptr dst_end) {
669   constexpr uptr granularity = ASAN_SHADOW_GRANULARITY;
670   // Last granule
671   uptr src_end_down = RoundDownTo(src_end, granularity);
672   uptr dst_end_down = RoundDownTo(dst_end, granularity);
673   if (dst_end_down == dst_end || !AddressIsPoisoned(dst_end))
674     return;
675   if (AddressIsPoisoned(src_end))
676     *(u8 *)MemToShadow(dst_end_down) = *(u8 *)MemToShadow(src_end_down);
677   else
678     SetContainerGranule(dst_end_down, src_end - src_end_down);
679 }
680 
681 // This function copies ASan memory annotations (poisoned/unpoisoned states)
682 // from one buffer to another.
683 // It's main purpose is to help with relocating trivially relocatable objects,
684 // which memory may be poisoned, without calling copy constructor.
685 // However, it does not move memory content itself, only annotations.
686 // If the buffers aren't aligned (the distance between buffers isn't
687 // granule-aligned)
688 //     // src_beg % granularity != dst_beg % granularity
689 // the function handles this by going byte by byte, slowing down performance.
690 // The old buffer annotations are not removed. If necessary,
691 // user can unpoison old buffer with __asan_unpoison_memory_region.
692 void __sanitizer_copy_contiguous_container_annotations(const void *src_beg_p,
693                                                        const void *src_end_p,
694                                                        const void *dst_beg_p,
695                                                        const void *dst_end_p) {
696   if (!flags()->detect_container_overflow)
697     return;
698 
699   VPrintf(3, "contiguous_container_src: %p %p\n", src_beg_p, src_end_p);
700   VPrintf(3, "contiguous_container_dst: %p %p\n", dst_beg_p, dst_end_p);
701 
702   uptr src_beg = reinterpret_cast<uptr>(src_beg_p);
703   uptr src_end = reinterpret_cast<uptr>(src_end_p);
704   uptr dst_beg = reinterpret_cast<uptr>(dst_beg_p);
705   uptr dst_end = reinterpret_cast<uptr>(dst_end_p);
706 
707   constexpr uptr granularity = ASAN_SHADOW_GRANULARITY;
708 
709   if (src_beg > src_end || (dst_end - dst_beg) != (src_end - src_beg)) {
710     GET_STACK_TRACE_FATAL_HERE;
711     ReportBadParamsToCopyContiguousContainerAnnotations(
712         src_beg, src_end, dst_beg, dst_end, &stack);
713   }
714 
715   if (src_beg == src_end || src_beg == dst_beg)
716     return;
717   // Due to support for overlapping buffers, we may have to copy elements
718   // in reversed order, when destination buffer starts in the middle of
719   // the source buffer (or shares first granule with it).
720   //
721   // When buffers are not granule-aligned (or distance between them,
722   // to be specific), annotatios have to be copied byte by byte.
723   //
724   // The only remaining edge cases involve edge granules,
725   // when the container starts or ends within a granule.
726   uptr src_beg_up = RoundUpTo(src_beg, granularity);
727   uptr src_end_up = RoundUpTo(src_end, granularity);
728   bool copy_in_reversed_order = src_beg < dst_beg && dst_beg <= src_end_up;
729   if (src_beg % granularity != dst_beg % granularity ||
730       RoundDownTo(dst_end - 1, granularity) <= dst_beg) {
731     if (copy_in_reversed_order)
732       SlowReversedCopyContainerAnnotations(src_beg, src_end, dst_beg, dst_end);
733     else
734       SlowCopyContainerAnnotations(src_beg, src_end, dst_beg, dst_end);
735     return;
736   }
737 
738   // As buffers are granule-aligned, we can just copy annotations of granules
739   // from the middle.
740   uptr dst_beg_up = RoundUpTo(dst_beg, granularity);
741   uptr dst_end_down = RoundDownTo(dst_end, granularity);
742   if (copy_in_reversed_order)
743     CopyContainerLastGranuleAnnotation(src_end, dst_end);
744   else
745     CopyContainerFirstGranuleAnnotation(src_beg, dst_beg);
746 
747   if (dst_beg_up < dst_end_down) {
748     internal_memmove((u8 *)MemToShadow(dst_beg_up),
749                      (u8 *)MemToShadow(src_beg_up),
750                      (dst_end_down - dst_beg_up) / granularity);
751   }
752 
753   if (copy_in_reversed_order)
754     CopyContainerFirstGranuleAnnotation(src_beg, dst_beg);
755   else
756     CopyContainerLastGranuleAnnotation(src_end, dst_end);
757 }
758 
759 static const void *FindBadAddress(uptr begin, uptr end, bool poisoned) {
760   CHECK_LE(begin, end);
761   constexpr uptr kMaxRangeToCheck = 32;
762   if (end - begin > kMaxRangeToCheck * 2) {
763     if (auto *bad = FindBadAddress(begin, begin + kMaxRangeToCheck, poisoned))
764       return bad;
765     if (auto *bad = FindBadAddress(end - kMaxRangeToCheck, end, poisoned))
766       return bad;
767   }
768 
769   for (uptr i = begin; i < end; ++i)
770     if (AddressIsPoisoned(i) != poisoned)
771       return reinterpret_cast<const void *>(i);
772   return nullptr;
773 }
774 
775 const void *__sanitizer_contiguous_container_find_bad_address(
776     const void *beg_p, const void *mid_p, const void *end_p) {
777   if (!flags()->detect_container_overflow)
778     return nullptr;
779   uptr granularity = ASAN_SHADOW_GRANULARITY;
780   uptr beg = reinterpret_cast<uptr>(beg_p);
781   uptr end = reinterpret_cast<uptr>(end_p);
782   uptr mid = reinterpret_cast<uptr>(mid_p);
783   CHECK_LE(beg, mid);
784   CHECK_LE(mid, end);
785   // If the byte after the storage is unpoisoned, everything in the granule
786   // before must stay unpoisoned.
787   uptr annotations_end =
788       (!AddrIsAlignedByGranularity(end) && !AddressIsPoisoned(end))
789           ? RoundDownTo(end, granularity)
790           : end;
791   beg = Min(beg, annotations_end);
792   mid = Min(mid, annotations_end);
793   if (auto *bad = FindBadAddress(beg, mid, false))
794     return bad;
795   if (auto *bad = FindBadAddress(mid, annotations_end, true))
796     return bad;
797   return FindBadAddress(annotations_end, end, false);
798 }
799 
800 int __sanitizer_verify_contiguous_container(const void *beg_p,
801                                             const void *mid_p,
802                                             const void *end_p) {
803   return __sanitizer_contiguous_container_find_bad_address(beg_p, mid_p,
804                                                            end_p) == nullptr;
805 }
806 
807 const void *__sanitizer_double_ended_contiguous_container_find_bad_address(
808     const void *storage_beg_p, const void *container_beg_p,
809     const void *container_end_p, const void *storage_end_p) {
810   if (!flags()->detect_container_overflow)
811     return nullptr;
812   uptr granularity = ASAN_SHADOW_GRANULARITY;
813   uptr storage_beg = reinterpret_cast<uptr>(storage_beg_p);
814   uptr storage_end = reinterpret_cast<uptr>(storage_end_p);
815   uptr beg = reinterpret_cast<uptr>(container_beg_p);
816   uptr end = reinterpret_cast<uptr>(container_end_p);
817 
818   // The prefix of the firs granule of the container is unpoisoned.
819   if (beg != end)
820     beg = Max(storage_beg, RoundDownTo(beg, granularity));
821 
822   // If the byte after the storage is unpoisoned, the prefix of the last granule
823   // is unpoisoned.
824   uptr annotations_end = (!AddrIsAlignedByGranularity(storage_end) &&
825                           !AddressIsPoisoned(storage_end))
826                              ? RoundDownTo(storage_end, granularity)
827                              : storage_end;
828   storage_beg = Min(storage_beg, annotations_end);
829   beg = Min(beg, annotations_end);
830   end = Min(end, annotations_end);
831 
832   if (auto *bad = FindBadAddress(storage_beg, beg, true))
833     return bad;
834   if (auto *bad = FindBadAddress(beg, end, false))
835     return bad;
836   if (auto *bad = FindBadAddress(end, annotations_end, true))
837     return bad;
838   return FindBadAddress(annotations_end, storage_end, false);
839 }
840 
841 int __sanitizer_verify_double_ended_contiguous_container(
842     const void *storage_beg_p, const void *container_beg_p,
843     const void *container_end_p, const void *storage_end_p) {
844   return __sanitizer_double_ended_contiguous_container_find_bad_address(
845              storage_beg_p, container_beg_p, container_end_p, storage_end_p) ==
846          nullptr;
847 }
848 
849 extern "C" SANITIZER_INTERFACE_ATTRIBUTE
850 void __asan_poison_intra_object_redzone(uptr ptr, uptr size) {
851   AsanPoisonOrUnpoisonIntraObjectRedzone(ptr, size, true);
852 }
853 
854 extern "C" SANITIZER_INTERFACE_ATTRIBUTE
855 void __asan_unpoison_intra_object_redzone(uptr ptr, uptr size) {
856   AsanPoisonOrUnpoisonIntraObjectRedzone(ptr, size, false);
857 }
858 
859 // --- Implementation of LSan-specific functions --- {{{1
860 namespace __lsan {
861 bool WordIsPoisoned(uptr addr) {
862   return (__asan_region_is_poisoned(addr, sizeof(uptr)) != 0);
863 }
864 }
865