|
| 1 | +/* |
| 2 | + * Demonstrate how to trick llvm scan-build's core.StackAddressEscape checker |
| 3 | + * via simple indirection. |
| 4 | + */ |
| 5 | + |
| 6 | +#include <stdio.h> |
| 7 | +#include <assert.h> |
| 8 | + |
| 9 | +struct chain_container { |
| 10 | + int * leaky_member; |
| 11 | + struct chain_container * previous; |
| 12 | +}; |
| 13 | + |
| 14 | +struct chain_container * sneaky_chain_container = 0; |
| 15 | + |
| 16 | +void |
| 17 | +escape_via_sneaky_chain_assignment_1(void) |
| 18 | +{ |
| 19 | + struct chain_container new_entry = {0,0}; |
| 20 | + int g = 1; |
| 21 | + fprintf(stderr, "&g = %p\n", &g); |
| 22 | + /* g escapes into global scope */ |
| 23 | + sneaky_chain_container->leaky_member = &g; |
| 24 | + /* Pointer to container is replaced with indirect pointer via chain */ |
| 25 | + new_entry.previous = sneaky_chain_container; |
| 26 | + sneaky_chain_container = &new_entry; |
| 27 | + |
| 28 | + /* |
| 29 | + * Restore container pointer from caller. |
| 30 | + * |
| 31 | + * scan-build has lost track of &g in its leaky_member now. |
| 32 | + */ |
| 33 | + sneaky_chain_container = sneaky_chain_container->previous; |
| 34 | + |
| 35 | + /* even though we definitely leak it */ |
| 36 | + assert(sneaky_chain_container->leaky_member == &g); |
| 37 | +} |
| 38 | + |
| 39 | +void |
| 40 | +escape_via_sneaky_chain_assignment(void) |
| 41 | +{ |
| 42 | + struct chain_container parent_sneaky = {0,0}; |
| 43 | + sneaky_chain_container = &parent_sneaky; |
| 44 | + escape_via_sneaky_chain_assignment_1(); |
| 45 | + /* |
| 46 | + * pointer to auto variable from escape_via_sneaky_chain_assignment_1 |
| 47 | + * has escaped. Dereferencing it would be a memory error. |
| 48 | + */ |
| 49 | + fprintf(stderr, "&g has escaped: %p\n", |
| 50 | + sneaky_chain_container->leaky_member); |
| 51 | + |
| 52 | + /* |
| 53 | + * Ensure we don't complain about &parent_sneaky escaping. |
| 54 | + */ |
| 55 | + sneaky_chain_container = 0; |
| 56 | +} |
| 57 | + |
| 58 | +int |
| 59 | +main(void) |
| 60 | +{ |
| 61 | + escape_via_sneaky_chain_assignment(); |
| 62 | + return 0; |
| 63 | +} |
0 commit comments