1// RUN: %clangxx_asan -O0 %s -o %t && not %run %t 2>&1 | FileCheck %s
2// RUN: %clangxx_asan -O1 %s -o %t && not %run %t 2>&1 | FileCheck %s
3// RUN: %clangxx_asan -O2 %s -o %t && not %run %t 2>&1 | FileCheck %s
4// RUN: %clangxx_asan -O3 %s -o %t && not %run %t 2>&1 | FileCheck %s
5
6// REQUIRES: compiler-rt-optimized
7// REQUIRES: stable-runtime
8
9#include <string.h>
10#include <stdlib.h>
11
12// We need a way to prevent the optimize from eliminating the
13// strncpy below (which otherwises writes to dead storage). We
14// need the read to be out-of-line to prevent memory forwarding
15// from making the memory dead again.
16int sink_memory(int N, char *p) __attribute__((noinline));
17int sink_memory(int N, char *p) {
18 int sum = 0;
19 for (int i = 0; i < N; i++)
20 sum += p[i];
21 return sum;
22}
23
24int main(int argc, char **argv) {
25 char *hello = (char*)malloc(size: 6);
26 strcpy(dest: hello, src: "hello");
27 int rval = sink_memory(N: 6, p: hello);
28 char *short_buffer = (char*)malloc(size: 9);
29 strncpy(dest: short_buffer, src: hello, n: 10); // BOOM
30 // CHECK: {{WRITE of size 10 at 0x.* thread T0}}
31 // CHECK: {{ #0 0x.* in .*strncpy}}
32 // CHECK: {{ #1 0x.* in main .*strncpy-overflow.cpp:}}[[@LINE-3]]
33 // CHECK: {{0x.* is located 0 bytes after 9-byte region}}
34 // CHECK: {{allocated by thread T0 here:}}
35 // CHECK: {{ #0 0x.* in .*malloc}}
36 // CHECK: {{ #[1-3] 0x.* in main .*strncpy-overflow.cpp:}}[[@LINE-8]]
37 return rval + sink_memory(N: 9, p: short_buffer);
38}
39

source code of compiler-rt/test/asan/TestCases/strncpy-overflow.cpp