123cd8d51SNico Weber // RUN: %clangxx_asan -O0 %s -o %t && not %run %t 2>&1 | FileCheck %s
223cd8d51SNico Weber // RUN: %clangxx_asan -O1 %s -o %t && not %run %t 2>&1 | FileCheck %s
323cd8d51SNico Weber // RUN: %clangxx_asan -O2 %s -o %t && not %run %t 2>&1 | FileCheck %s
423cd8d51SNico Weber // RUN: %clangxx_asan -O3 %s -o %t && not %run %t 2>&1 | FileCheck %s
5673dc3d4SNico Weber
6673dc3d4SNico Weber // REQUIRES: compiler-rt-optimized
7673dc3d4SNico Weber // REQUIRES: stable-runtime
8673dc3d4SNico Weber
9673dc3d4SNico Weber #include <string.h>
10673dc3d4SNico Weber #include <stdlib.h>
11*9b955f77SPhilip Reames
12*9b955f77SPhilip Reames // We need a way to prevent the optimize from eliminating the
13*9b955f77SPhilip Reames // strncpy below (which otherwises writes to dead storage). We
14*9b955f77SPhilip Reames // need the read to be out-of-line to prevent memory forwarding
15*9b955f77SPhilip Reames // from making the memory dead again.
16*9b955f77SPhilip Reames int sink_memory(int N, char *p) __attribute__((noinline));
sink_memory(int N,char * p)17*9b955f77SPhilip Reames int sink_memory(int N, char *p) {
18*9b955f77SPhilip Reames int sum = 0;
19*9b955f77SPhilip Reames for (int i = 0; i < N; i++)
20*9b955f77SPhilip Reames sum += p[i];
21*9b955f77SPhilip Reames return sum;
22*9b955f77SPhilip Reames }
23*9b955f77SPhilip Reames
main(int argc,char ** argv)24673dc3d4SNico Weber int main(int argc, char **argv) {
25673dc3d4SNico Weber char *hello = (char*)malloc(6);
26673dc3d4SNico Weber strcpy(hello, "hello");
27*9b955f77SPhilip Reames int rval = sink_memory(6, hello);
28673dc3d4SNico Weber char *short_buffer = (char*)malloc(9);
29673dc3d4SNico Weber strncpy(short_buffer, hello, 10); // BOOM
30673dc3d4SNico Weber // CHECK: {{WRITE of size 10 at 0x.* thread T0}}
3123cd8d51SNico Weber // CHECK: {{ #0 0x.* in .*strncpy}}
3223cd8d51SNico Weber // CHECK: {{ #1 0x.* in main .*strncpy-overflow.cpp:}}[[@LINE-3]]
33673dc3d4SNico Weber // CHECK: {{0x.* is located 0 bytes to the right of 9-byte region}}
34673dc3d4SNico Weber // CHECK: {{allocated by thread T0 here:}}
3523cd8d51SNico Weber // CHECK: {{ #0 0x.* in .*malloc}}
3623cd8d51SNico Weber // CHECK: {{ #1 0x.* in main .*strncpy-overflow.cpp:}}[[@LINE-8]]
37*9b955f77SPhilip Reames return rval + sink_memory(9, short_buffer);
38673dc3d4SNico Weber }
39