You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Invalid down casts are a source of vulnerabilities.
Its allowance in static_cast - which is otherwise
relatively safe - are recognized as dangerous by
various safety guidelines such as the core guidelines and misra.
While there exist a clang-tidy check, it seems reasonable,
in the interest of safety to warn about that construct in clang
and to propose its deprecation in WG21.
This is inspired by
[p3081r0](https://www.open-std.org/jtc1/sc22/wg21/docs/papers/2024/p3081r0.pdf)
which propose to promote static_cast to dynamic_cast silently, which
would have further issues (suddently static_cast could produce a null pointer).
Part of the goal of this PR is therefore to demonstrate the viability
of deprecating this construct.
Copy file name to clipboardExpand all lines: clang/test/Analysis/cast-to-struct.cpp
+4-3Lines changed: 4 additions & 3 deletions
Original file line number
Diff line number
Diff line change
@@ -41,20 +41,21 @@ void structToStruct(struct AB *P) {
41
41
Base &B1 = D1;
42
42
D2 = (Derived *)&B1;
43
43
D2 = dynamic_cast<Derived *>(&B1);
44
-
D2 = static_cast<Derived *>(&B1);
44
+
D2 = static_cast<Derived *>(&B1);// expected-warning {{static downcast from 'Base' to 'Derived'}}
45
45
46
46
// True positives when casting from Base to Derived.
47
47
Base B2;
48
48
D2 = (Derived *)&B2;// expected-warning {{Casting data to a larger structure type and accessing a field can lead to memory access errors or data corruption}}
49
49
D2 = dynamic_cast<Derived *>(&B2);// expected-warning {{Casting data to a larger structure type and accessing a field can lead to memory access errors or data corruption}}
50
-
D2 = static_cast<Derived *>(&B2);// expected-warning {{Casting data to a larger structure type and accessing a field can lead to memory access errors or data corruption}}
50
+
D2 = static_cast<Derived *>(&B2);// expected-warning {{Casting data to a larger structure type and accessing a field can lead to memory access errors or data corruption}} \
51
+
// expected-warning {{static downcast from 'Base' to 'Derived'}}
51
52
52
53
// False negatives, cast from Base to Derived. With path sensitive analysis
53
54
// these false negatives could be fixed.
54
55
Base *B3 = &B2;
55
56
D2 = (Derived *)B3;
56
57
D2 = dynamic_cast<Derived *>(B3);
57
-
D2 = static_cast<Derived *>(B3);
58
+
D2 = static_cast<Derived *>(B3);// expected-warning {{static downcast from 'Base' to 'Derived'}}
0 commit comments