| 1 |
// RUN: %clang_analyze_cc1 -analyzer-checker=alpha.core.StoreToImmutable -std=c++17 -verify %s |
| 2 |
|
| 3 |
void test_write_to_const_ref_param(const int ¶m) { |
| 4 |
*(int*)¶m = 100; // expected-warning {{Trying to write to immutable memory}} |
| 5 |
} |
| 6 |
|
| 7 |
// FIXME: This should warn in C mode too. |
| 8 |
void test_write_to_string_literal() { |
| 9 |
char *str = (char*)"hello"; |
| 10 |
str[0] = 'H'; // expected-warning {{Trying to write to immutable memory}} |
| 11 |
} |
| 12 |
|
| 13 |
struct ParamStruct { |
| 14 |
const int z; // expected-note {{Memory region is declared as immutable here}} |
| 15 |
int w; |
| 16 |
}; |
| 17 |
|
| 18 |
void test_write_to_const_struct_ref_param(const ParamStruct &s) { |
| 19 |
*(int*)&s.z = 100; // expected-warning {{Trying to write to immutable memory}} |
| 20 |
} |
| 21 |
|
| 22 |
void test_const_ref_to_nonconst_data() { |
| 23 |
int data = 42; |
| 24 |
const int &ref = data; |
| 25 |
*(int*)&ref = 100; // No warning expected |
| 26 |
} |
| 27 |
|
| 28 |
void test_const_ref_to_const_data() { |
| 29 |
const int data = 42; // expected-note {{Memory region is declared as immutable here}} |
| 30 |
const int &ref = data; |
| 31 |
*(int*)&ref = 100; // expected-warning {{Trying to write to immutable memory}} |
| 32 |
} |
| 33 |
|
| 34 |
void test_ref_to_nonconst_data() { |
| 35 |
int data = 42; |
| 36 |
int &ref = data; |
| 37 |
ref = 100; // No warning expected |
| 38 |
} |
| 39 |
|
| 40 |
void test_ref_to_const_data() { |
| 41 |
const int data = 42; // expected-note {{Memory region is declared as immutable here}} |
| 42 |
int &ref = *(int*)&data; |
| 43 |
ref = 100; // expected-warning {{Trying to write to immutable memory}} |
| 44 |
} |
| 45 |
|
| 46 |
struct MultipleLayerStruct { |
| 47 |
MultipleLayerStruct(); |
| 48 |
const int data; // expected-note {{Memory region is declared as immutable here}} |
| 49 |
const int buf[10]; // expected-note {{Enclosing memory region is declared as immutable here}} |
| 50 |
}; |
| 51 |
|
| 52 |
MultipleLayerStruct MLS[10]; |
| 53 |
|
| 54 |
void test_multiple_layer_struct_array_member() { |
| 55 |
int *p = (int*)&MLS[2].data; |
| 56 |
*p = 4; // expected-warning {{Trying to write to immutable memory}} |
| 57 |
} |
| 58 |
|
| 59 |
void test_multiple_layer_struct_array_array_member() { |
| 60 |
int *p = (int*)&MLS[2].buf[3]; |
| 61 |
*p = 4; // expected-warning {{Trying to write to immutable memory}} |
| 62 |
} |
| 63 |
|
| 64 |
struct StructWithNonConstMember { |
| 65 |
int x; |
| 66 |
}; |
| 67 |
|
| 68 |
const StructWithNonConstMember SWNCM{0}; // expected-note {{Enclosing memory region is declared as immutable here}} |
| 69 |
|
| 70 |
void test_write_to_non_const_member_of_const_struct() { |
| 71 |
*(int*)&SWNCM.x = 100; // expected-warning {{Trying to write to immutable memory in global read-only storage}} |
| 72 |
} |