| 1 |
/* Example of a multilevel wrapper around malloc, with an unchecked write. */ |
| 2 |
|
| 3 |
/* { dg-additional-options "-fdiagnostics-show-line-numbers -fdiagnostics-path-format=inline-events -fanalyzer-checker=malloc -fdiagnostics-show-caret" } */ |
| 4 |
/* { dg-enable-nn-line-numbers "" } */ |
| 5 |
|
| 6 |
/* C only; attempting to generalize it for C++ leads |
| 7 |
to an explosion of possibilities for the multiline output. */ |
| 8 |
|
| 9 |
#include <stdlib.h> |
| 10 |
|
| 11 |
void *wrapped_malloc (size_t size) |
| 12 |
{ |
| 13 |
return malloc (size); |
| 14 |
} |
| 15 |
|
| 16 |
typedef struct boxed_int |
| 17 |
{ |
| 18 |
int i; |
| 19 |
} boxed_int; |
| 20 |
|
| 21 |
boxed_int * |
| 22 |
make_boxed_int (int i) |
| 23 |
{ |
| 24 |
boxed_int *result = (boxed_int *)wrapped_malloc (sizeof (boxed_int)); |
| 25 |
result->i = i; /* { dg-warning "dereference of possibly-NULL 'result'" } */ |
| 26 |
return result; |
| 27 |
} |
| 28 |
|
| 29 |
/* "dereference of possibly-NULL 'result' [CWE-690]". */ |
| 30 |
/* { dg-begin-multiline-output "" } |
| 31 |
NN | result->i = i; |
| 32 |
| ~~~~~~~~~~^~~ |
| 33 |
'make_boxed_int': events 1-2 |
| 34 |
| |
| 35 |
| NN | make_boxed_int (int i) |
| 36 |
| | ^~~~~~~~~~~~~~ |
| 37 |
| | | |
| 38 |
| | (1) entry to 'make_boxed_int' |
| 39 |
| NN | { |
| 40 |
| NN | boxed_int *result = (boxed_int *)wrapped_malloc (sizeof (boxed_int)); |
| 41 |
| | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ |
| 42 |
| | | |
| 43 |
| | (2) calling 'wrapped_malloc' from 'make_boxed_int' |
| 44 |
| |
| 45 |
+--> 'wrapped_malloc': events 3-4 |
| 46 |
| |
| 47 |
| NN | void *wrapped_malloc (size_t size) |
| 48 |
| | ^~~~~~~~~~~~~~ |
| 49 |
| | | |
| 50 |
| | (3) entry to 'wrapped_malloc' |
| 51 |
| NN | { |
| 52 |
| NN | return malloc (size); |
| 53 |
| | ~~~~~~~~~~~~~ |
| 54 |
| | | |
| 55 |
| | (4) this call could return NULL |
| 56 |
| |
| 57 |
<------+ |
| 58 |
| |
| 59 |
'make_boxed_int': events 5-6 |
| 60 |
| |
| 61 |
| NN | boxed_int *result = (boxed_int *)wrapped_malloc (sizeof (boxed_int)); |
| 62 |
| | ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ |
| 63 |
| | | |
| 64 |
| | (5) possible return of NULL to 'make_boxed_int' from 'wrapped_malloc' |
| 65 |
| NN | result->i = i; |
| 66 |
| | ~~~~~~~~~~~~~ |
| 67 |
| | | |
| 68 |
| | (6) 'result' could be NULL: unchecked value from (4) |
| 69 |
| |
| 70 |
{ dg-end-multiline-output "" } */ |