[clang] [clang][analyzer] Support `PointerType` in `getCXXRecordDecl` for `ContainerModeling` (PR #87787)
Junjie Shen via cfe-commits
cfe-commits at lists.llvm.org
Fri Apr 5 08:04:42 PDT 2024
https://github.com/shenjunjiekoda updated https://github.com/llvm/llvm-project/pull/87787
>From 2f82a7c0f627fc594ed7cd9b92b464856a364cec Mon Sep 17 00:00:00 2001
From: Shenjunjie <shenjunjiekoda at foxmail.com>
Date: Fri, 5 Apr 2024 10:35:03 -0400
Subject: [PATCH] [clang][analyzer] Support `PointerType` in `getCXXRecordDecl`
for `ContainerModeling`.
Previously, `getCXXRecordDecl` did not account for `PointerType` cases, which limited its ability to model containers that use pointers rather than references. This change was necessary for accurately modeling `cont_with_ptr_iterator<int>` and similar containers, ensuring static analysis can correctly flag potential iterator invalidation issues, as demonstrated in the added test case.
---
.../lib/StaticAnalyzer/Checkers/ContainerModeling.cpp | 4 ++++
clang/test/Analysis/invalidated-iterator.cpp | 10 +++++++++-
2 files changed, 13 insertions(+), 1 deletion(-)
diff --git a/clang/lib/StaticAnalyzer/Checkers/ContainerModeling.cpp b/clang/lib/StaticAnalyzer/Checkers/ContainerModeling.cpp
index 65a2ec4076fdf6..009c0d3fb93686 100644
--- a/clang/lib/StaticAnalyzer/Checkers/ContainerModeling.cpp
+++ b/clang/lib/StaticAnalyzer/Checkers/ContainerModeling.cpp
@@ -770,6 +770,10 @@ const CXXRecordDecl *getCXXRecordDecl(ProgramStateRef State,
Type = RefT->getPointeeType();
}
+ if (const auto *PtrT = Type->getAs<PointerType>()) {
+ Type = PtrT->getPointeeType();
+ }
+
return Type->getUnqualifiedDesugaredType()->getAsCXXRecordDecl();
}
diff --git a/clang/test/Analysis/invalidated-iterator.cpp b/clang/test/Analysis/invalidated-iterator.cpp
index 778a8e01d99380..c940dbf7276d34 100644
--- a/clang/test/Analysis/invalidated-iterator.cpp
+++ b/clang/test/Analysis/invalidated-iterator.cpp
@@ -130,6 +130,14 @@ struct cont_with_ptr_iterator {
T* erase(T*);
};
+void invalidated_access_via_end_iterator_after_push_back() {
+ cont_with_ptr_iterator<int> C;
+ C.push_back(1);
+ auto i = C.end();
+ C.push_back(2);
+ auto j = i[-1]; // expected-warning{{Invalidated iterator accessed}}
+}
+
void invalidated_dereference_end_ptr_iterator(cont_with_ptr_iterator<int> &C) {
auto i = C.begin();
C.erase(i);
@@ -196,4 +204,4 @@ void invalidated_subscript_end_ptr_iterator(cont_with_ptr_iterator<int> &C) {
auto i = C.begin();
C.erase(i);
(void) i[1]; // expected-warning{{Invalidated iterator accessed}}
-}
+}
\ No newline at end of file
More information about the cfe-commits
mailing list