| 1 |
typedef __SIZE_TYPE__ size_t; |
| 2 |
#include "../../gcc.dg/analyzer/analyzer-decls.h" |
| 3 |
|
| 4 |
/* Concatenating a pair of strings. */ |
| 5 |
|
| 6 |
/* Correct but poor implementation with repeated __builtin_strlen calls. */ |
| 7 |
|
| 8 |
char * |
| 9 |
alloc_dup_of_concatenated_pair_1_correct (const char *x, const char *y) |
| 10 |
{ |
| 11 |
size_t sz = __builtin_strlen (x) + __builtin_strlen (y) + 1; |
| 12 |
char *result = (char *) __builtin_malloc (sz); |
| 13 |
if (!result) |
| 14 |
return NULL; |
| 15 |
__builtin_memcpy (result, x, __builtin_strlen (x)); |
| 16 |
__builtin_memcpy (result + __builtin_strlen (x), y, __builtin_strlen (y)); |
| 17 |
result[__builtin_strlen(x) + __builtin_strlen (y)] = '\0'; |
| 18 |
return result; |
| 19 |
} |
| 20 |
|
| 21 |
/* Incorrect version: forgetting to add space for terminator. */ |
| 22 |
|
| 23 |
char * |
| 24 |
alloc_dup_of_concatenated_pair_1_incorrect (const char *x, const char *y) |
| 25 |
{ |
| 26 |
/* Forgetting to add space for the terminator here. */ |
| 27 |
size_t sz = __builtin_strlen (x) + __builtin_strlen (y); |
| 28 |
char *result = (char *) __builtin_malloc (sz); |
| 29 |
if (!result) |
| 30 |
return NULL; |
| 31 |
__builtin_memcpy (result, x, __builtin_strlen (x)); |
| 32 |
__builtin_memcpy (result + __builtin_strlen (x), y, __builtin_strlen (y)); |
| 33 |
result[__builtin_strlen(x) + __builtin_strlen (y)] = '\0'; /* { dg-warning "heap-based buffer overflow" "PR analyzer/105899" { xfail *-*-* } } */ |
| 34 |
return result; |
| 35 |
} |
| 36 |
|
| 37 |
/* As above, but only calling __builtin_strlen once on each input. */ |
| 38 |
|
| 39 |
char * |
| 40 |
alloc_dup_of_concatenated_pair_2_correct (const char *x, const char *y) |
| 41 |
{ |
| 42 |
size_t len_x = __builtin_strlen (x); |
| 43 |
size_t len_y = __builtin_strlen (y); |
| 44 |
size_t sz = len_x + len_y + 1; |
| 45 |
char *result = (char *) __builtin_malloc (sz); |
| 46 |
if (!result) |
| 47 |
return NULL; |
| 48 |
__builtin_memcpy (result, x, len_x); |
| 49 |
__builtin_memcpy (result + len_x, y, len_y); |
| 50 |
result[len_x + len_y] = '\0'; |
| 51 |
return result; |
| 52 |
} |
| 53 |
|
| 54 |
char * |
| 55 |
alloc_dup_of_concatenated_pair_2_incorrect (const char *x, const char *y) |
| 56 |
{ |
| 57 |
size_t len_x = __builtin_strlen (x); |
| 58 |
size_t len_y = __builtin_strlen (y); |
| 59 |
size_t sz = len_x + len_y; /* Forgetting to add space for the terminator. */ |
| 60 |
char *result = (char *) __builtin_malloc (sz); /* { dg-message "capacity: 'len_x \\+ len_y' bytes" "" { target c } } */ |
| 61 |
/* { dg-message "capacity: '\\(len_x \\+ len_y\\)' bytes" "" { target c++ } .-1 } */ |
| 62 |
if (!result) |
| 63 |
return NULL; |
| 64 |
__builtin_memcpy (result, x, len_x); |
| 65 |
__builtin_memcpy (result + len_x, y, len_y); |
| 66 |
result[len_x + len_y] = '\0'; /* { dg-warning "heap-based buffer overflow" } */ |
| 67 |
return result; |
| 68 |
} |