[clang] [clang][dataflow]Use cast_or_null instead cast to prevent crash (PR #68510)

Qizhi Hu via cfe-commits cfe-commits at lists.llvm.org
Mon Oct 9 22:36:18 PDT 2023


https://github.com/jcsxky updated https://github.com/llvm/llvm-project/pull/68510

>From 7a8c515c70bb06ae886c8c434d9d3a79a152d115 Mon Sep 17 00:00:00 2001
From: huqizhi <huqizhi at feysh.com>
Date: Sun, 8 Oct 2023 16:00:29 +0800
Subject: [PATCH] [clang][analysis]Use dyn_cast_or_null instead cast to prevent
 crash

---
 .../bugprone/unchecked-optional-access.cpp    | 41 +++++++++++++++++++
 .../Models/UncheckedOptionalAccessModel.cpp   |  2 +-
 2 files changed, 42 insertions(+), 1 deletion(-)

diff --git a/clang-tools-extra/test/clang-tidy/checkers/bugprone/unchecked-optional-access.cpp b/clang-tools-extra/test/clang-tidy/checkers/bugprone/unchecked-optional-access.cpp
index 1921291f2187d92..c797a263a3220b8 100644
--- a/clang-tools-extra/test/clang-tidy/checkers/bugprone/unchecked-optional-access.cpp
+++ b/clang-tools-extra/test/clang-tidy/checkers/bugprone/unchecked-optional-access.cpp
@@ -180,3 +180,44 @@ void std_forward_rvalue_ref_safe(absl::optional<int>&& opt) {
 
   std::forward<absl::optional<int>>(opt).value();
 }
+
+namespace std {
+
+template<typename T>
+class optional {
+public:
+	template <typename U>
+  optional& operator=(const U &u){
+		data = u;
+	}
+private:
+  T data;
+};
+
+template <typename T>
+class vector {
+public:
+  vector() {}
+  T &operator[](unsigned long index) { return data[index]; }
+  bool empty() { return size == 0UL; }
+
+private:
+  T *data;
+  unsigned long size;
+};
+
+} // namespace std
+
+struct LinearGradient {
+  struct Stop {
+    std::optional<float> position;
+  };
+  std::vector<Stop> stops;
+};
+
+
+void use_dyn_cast_or_null() {
+	LinearGradient gradient;
+	if (!gradient.stops.empty())
+	  gradient.stops[0].position = 0;
+}
diff --git a/clang/lib/Analysis/FlowSensitive/Models/UncheckedOptionalAccessModel.cpp b/clang/lib/Analysis/FlowSensitive/Models/UncheckedOptionalAccessModel.cpp
index f61f26ff27804ec..8bd9a030f50cda0 100644
--- a/clang/lib/Analysis/FlowSensitive/Models/UncheckedOptionalAccessModel.cpp
+++ b/clang/lib/Analysis/FlowSensitive/Models/UncheckedOptionalAccessModel.cpp
@@ -599,7 +599,7 @@ void transferAssignment(const CXXOperatorCallExpr *E, BoolValue &HasValueVal,
                         LatticeTransferState &State) {
   assert(E->getNumArgs() > 0);
 
-  if (auto *Loc = cast<RecordStorageLocation>(
+  if (auto *Loc = cast_or_null<RecordStorageLocation>(
           State.Env.getStorageLocation(*E->getArg(0)))) {
     createOptionalValue(*Loc, HasValueVal, State.Env);
 



More information about the cfe-commits mailing list