| 1 |
/* { dg-additional-options "-fanalyzer-call-summaries --param analyzer-min-snodes-for-call-summary=0" } */ |
| 2 |
/* { dg-skip-if "requires hosted libstdc++ for stdlib malloc" { ! hostedlib } } */ |
| 3 |
|
| 4 |
/* There need to be at least two calls to a function for the |
| 5 |
call-summarization code to be used. |
| 6 |
TODO: add some kind of test that summarization *was* used. */ |
| 7 |
|
| 8 |
#include <stdlib.h> |
| 9 |
#include <string.h> |
| 10 |
#include "../../gcc.dg/analyzer/analyzer-decls.h" |
| 11 |
|
| 12 |
int *malloc_int (int i) |
| 13 |
{ |
| 14 |
int *res = (int *) malloc (sizeof (int)); |
| 15 |
if (!res) |
| 16 |
return NULL; |
| 17 |
*res = i; |
| 18 |
return res; |
| 19 |
} |
| 20 |
|
| 21 |
void test_malloc_int (int x) |
| 22 |
{ |
| 23 |
int *p, *q; |
| 24 |
|
| 25 |
p = malloc_int (42); |
| 26 |
if (p) |
| 27 |
__analyzer_eval (*p == 42); /* { dg-warning "TRUE" } */ |
| 28 |
free (p); |
| 29 |
|
| 30 |
q = malloc_int (x); |
| 31 |
if (q) |
| 32 |
__analyzer_eval (*q == x); /* { dg-warning "TRUE" } */ |
| 33 |
free (q); |
| 34 |
} |
| 35 |
|
| 36 |
void test_leak (int x) |
| 37 |
{ |
| 38 |
int *p = malloc_int (x); /* { dg-message "when 'malloc_int' returns pointer to heap-allocated buffer" "" { target c } } */ |
| 39 |
/* { dg-message "when 'int\\* malloc_int\\(int\\)' returns pointer to heap-allocated buffer" "" { target c++ } .-1 } */ |
| 40 |
} /* { dg-message "leak of 'p'" } */ |
| 41 |
|
| 42 |
void *wrapped_malloc (size_t sz) |
| 43 |
{ |
| 44 |
return malloc (sz); |
| 45 |
} |
| 46 |
|
| 47 |
void wrapped_free (void *p) |
| 48 |
{ |
| 49 |
free (p); |
| 50 |
} |
| 51 |
|
| 52 |
void test_wrapped_malloc_and_free (size_t sz) |
| 53 |
{ |
| 54 |
void *p = wrapped_malloc (100); |
| 55 |
void *q = wrapped_malloc (sz); |
| 56 |
__analyzer_dump_capacity (p); /* { dg-warning "capacity: '\\(\[^\n\r\]*\\)100'" } */ |
| 57 |
__analyzer_dump_capacity (q); /* { dg-warning "capacity: 'INIT_VAL\\(sz_\[^\n\r\]*\\)'" } */ |
| 58 |
wrapped_free (p); |
| 59 |
wrapped_free (q); |
| 60 |
} |
| 61 |
|
| 62 |
void test_use_after_free (void) |
| 63 |
{ |
| 64 |
// TODO |
| 65 |
} |
| 66 |
|
| 67 |
void test_use_without_check (size_t sz) |
| 68 |
{ |
| 69 |
char *buf = (char *) wrapped_malloc (sz); /* { dg-message "this call could return NULL" } */ |
| 70 |
memset (buf, 'x', 4); /* { dg-warning "use of possibly-NULL 'buf' where non-null expected" } */ |
| 71 |
wrapped_free (buf); |
| 72 |
} |
| 73 |
|
| 74 |
void test_out_of_bounds (size_t sz) |
| 75 |
{ |
| 76 |
char *buf = (char *) wrapped_malloc (sz); |
| 77 |
if (!buf) |
| 78 |
return; |
| 79 |
memset (buf, 'x', sz); |
| 80 |
buf[sz] = '\0'; /* { dg-warning "heap-based buffer overflow" } */ |
| 81 |
wrapped_free (buf); |
| 82 |
} |