xref: /llvm-project/compiler-rt/test/asan/TestCases/alloca_vla_interact.cpp (revision 23d209f350f4e51b2a42636ce45d10c6e208252d)
1673dc3d4SNico Weber // RUN: %clangxx_asan -O0 -mllvm -asan-instrument-dynamic-allocas %s -o %t
2673dc3d4SNico Weber // RUN: %run %t 2>&1
3673dc3d4SNico Weber //
4673dc3d4SNico Weber // REQUIRES: stable-runtime
5673dc3d4SNico Weber 
6*23d209f3SKoakuma // See https://github.com/llvm/llvm-project/issues/110956
7*23d209f3SKoakuma // XFAIL: target=sparc{{.*}}
8*23d209f3SKoakuma 
9673dc3d4SNico Weber // This testcase checks correct interaction between VLAs and allocas.
10673dc3d4SNico Weber 
11673dc3d4SNico Weber #include <assert.h>
12673dc3d4SNico Weber #include <stdint.h>
13673dc3d4SNico Weber #include <stdlib.h>
14673dc3d4SNico Weber #include "sanitizer/asan_interface.h"
15673dc3d4SNico Weber 
16673dc3d4SNico Weber // MSVC provides _alloca instead of alloca.
17673dc3d4SNico Weber #if defined(_MSC_VER) && !defined(alloca)
18673dc3d4SNico Weber # define alloca _alloca
19673dc3d4SNico Weber #endif
20673dc3d4SNico Weber 
21673dc3d4SNico Weber #if defined(__sun__) && defined(__svr4__)
22673dc3d4SNico Weber #include <alloca.h>
23673dc3d4SNico Weber #endif
24673dc3d4SNico Weber 
25673dc3d4SNico Weber #define RZ 32
26673dc3d4SNico Weber 
27673dc3d4SNico Weber __attribute__((noinline)) void foo(int len) {
28673dc3d4SNico Weber   char *top, *bot;
29673dc3d4SNico Weber   // This alloca call should live until the end of foo.
30673dc3d4SNico Weber   char *alloca1 = (char *)alloca(len);
31673dc3d4SNico Weber   assert(!(reinterpret_cast<uintptr_t>(alloca1) & 31L));
32673dc3d4SNico Weber   // This should be first poisoned address after loop.
33673dc3d4SNico Weber   top = alloca1 - RZ;
34673dc3d4SNico Weber   for (int i = 0; i < 32; ++i) {
35673dc3d4SNico Weber     // Check that previous alloca was unpoisoned at the end of iteration.
36673dc3d4SNico Weber     if (i) assert(!__asan_region_is_poisoned(bot, 96));
37673dc3d4SNico Weber     // VLA is unpoisoned at the end of iteration.
38673dc3d4SNico Weber     volatile char array[i];
397740565fSFangrui Song     // Ensure that asan-use-stack-safety does not optimize out the poisoning.
407740565fSFangrui Song     if (i) array[0] = 0;
41673dc3d4SNico Weber     assert(!(reinterpret_cast<uintptr_t>(array) & 31L));
42673dc3d4SNico Weber     // Alloca is unpoisoned at the end of iteration,
43673dc3d4SNico Weber     // because dominated by VLA.
44673dc3d4SNico Weber     bot = (char *)alloca(i) - RZ;
45673dc3d4SNico Weber   }
46673dc3d4SNico Weber   // Check that all allocas from loop were unpoisoned correctly.
47673dc3d4SNico Weber   void *q = __asan_region_is_poisoned(bot, (char *)top - (char *)bot + 1);
48673dc3d4SNico Weber   assert(q == top);
49673dc3d4SNico Weber }
50673dc3d4SNico Weber 
51673dc3d4SNico Weber int main(int argc, char **argv) {
52673dc3d4SNico Weber   foo(32);
53673dc3d4SNico Weber   return 0;
54673dc3d4SNico Weber }
55