Debian Codegraph @

gcc/testsuite/c-c++-common/analyzer/flexible-array-member-1.c

raw
1 /* { dg-skip-if "requires hosted libstdc++ for stdlib malloc" { ! hostedlib } } */
2
3 #include <stdlib.h>
4 #include <string.h>
5 #include "../../gcc.dg/analyzer/analyzer-decls.h"
6
7 struct str {
8 size_t len;
9 char data[];
10 };
11
12 struct str *
13 test_const_size (void)
14 {
15 struct str *str = (struct str *) malloc(sizeof(str) + 10);
16 if (str) {
17 str->len = 10;
18 memset(str->data, 'x', 10);
19 return str;
20 }
21 return NULL;
22 }
23
24 struct str *
25 test_const_size_oob_1 (void)
26 {
27 /* Forgetting to add space for the trailing array. */
28 struct str *str = (struct str *) malloc(sizeof(str));
29 if (str) {
30 str->len = 10;
31 memset(str->data, 'x', 10); /* { dg-warning "heap-based buffer overflow" "Wanalyzer-out-of-bounds" } */
32 /* { dg-warning "'\[^\n\r\]*memset\[^\n\r\]*' writing 10 bytes into a region of size 0 overflows the destination" "Wstringop-overflow" { target *-*-* } .-1 } */
33 return str;
34 }
35 return NULL;
36 }
37
38 struct str *
39 test_const_size_oob_2 (void)
40 {
41 struct str *str = (struct str *) malloc(sizeof(str) + 10);
42 if (str) {
43 str->len = 10;
44 /* Using the wrong size here. */
45 memset(str->data, 'x', 11); /* { dg-warning "heap-based buffer overflow" "Wanalyzer-out-of-bounds" } */
46 /* { dg-warning "'\[^\n\r\]*memset\[^\n\r\]*' writing 11 bytes into a region of size 10 overflows the destination" "Wstringop-overflow" { target *-*-* } .-1 } */
47
48 return str;
49 }
50 return NULL;
51 }
52
53 struct str *
54 test_symbolic_size (size_t len)
55 {
56 struct str *str = (struct str *) malloc(sizeof(str) + len);
57 if (str) {
58 str->len = len;
59 memset(str->data, 'x', len);
60 return str;
61 }
62 return NULL;
63 }
64
65 struct str *
66 test_symbolic_size_oob (size_t len)
67 {
68 /* Forgetting to add space for the trailing array. */
69 struct str *str = (struct str *) malloc(sizeof(str));
70 if (str) {
71 str->len = len;
72 memset(str->data, 'x', len); /* { dg-warning "heap-based buffer overflow" "PR analyzer/98247" { xfail *-*-* } } */
73 // TODO(xfail): we don't yet complain about this case, which occurs when len > 0
74 return str;
75 }
76 return NULL;
77 }
78
79 struct str *
80 test_symbolic_size_with_terminator (size_t len)
81 {
82 struct str *str = (struct str *) malloc(sizeof(str) + len + 1);
83 if (str) {
84 str->len = len;
85 memset(str->data, 'x', len);
86 str->data[len] = '\0';
87 return str;
88 }
89 return NULL;
90 }
91
92 struct str *
93 test_symbolic_size_with_terminator_oob (size_t len)
94 {
95 /* Forgetting to add 1 for the terminator. */
96 struct str *str = (struct str *) malloc(sizeof(str) + len);
97 if (str) {
98 str->len = len;
99 memset(str->data, 'x', len);
100 str->data[len] = '\0'; /* { dg-warning "heap-based buffer overflow" } */
101 return str;
102 }
103 return NULL;
104 }