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

Provided by KDAB

Privacy Policy
Improve your Profiling and Debugging skills
Find out more

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