[clang] [Clang][Parser] Fix crash of clang when trying to convert a cast to … (PR #78840)

via cfe-commits cfe-commits at lists.llvm.org
Sat Jan 20 02:32:46 PST 2024


https://github.com/ChipsSpectre created https://github.com/llvm/llvm-project/pull/78840

…a nullptr casted to an array of non-constant size to a reference (#76634).

This situation is undefined behavior, and should not lead to a compiler crash. Thus, the problematic cast is only executed on non-null pointers.

Fixes one reason for a crash in #76634.

>From 2503669a55f8dae534440a4eacb66a4500f78e3f Mon Sep 17 00:00:00 2001
From: ChipsSpectre <maximilian.hornung at tum.de>
Date: Sat, 20 Jan 2024 11:26:32 +0100
Subject: [PATCH]  [Clang][Parser] Fix crash of clang when trying to convert a
 cast to a nullptr casted to an array of non-constant size to a reference
 (#76634).

This situation is undefined behavior, and should not lead to a compiler crash.
Thus, the problematic cast is only executed on non-null pointers.

Fixes one reason for a crash in #76634.
---
 clang/lib/AST/ExprConstant.cpp | 13 ++++++++++---
 1 file changed, 10 insertions(+), 3 deletions(-)

diff --git a/clang/lib/AST/ExprConstant.cpp b/clang/lib/AST/ExprConstant.cpp
index f1d07d022b25848..165046bd06e92a9 100644
--- a/clang/lib/AST/ExprConstant.cpp
+++ b/clang/lib/AST/ExprConstant.cpp
@@ -9272,10 +9272,17 @@ bool PointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
     }
     // The result is a pointer to the first element of the array.
     auto *AT = Info.Ctx.getAsArrayType(SubExpr->getType());
-    if (auto *CAT = dyn_cast<ConstantArrayType>(AT))
+    if (auto *CAT = dyn_cast<ConstantArrayType>(AT)) {
       Result.addArray(Info, E, CAT);
-    else
-      Result.addUnsizedArray(Info, E, AT->getElementType());
+    }
+    else {
+      if (Result.checkNullPointer(Info, E, CSK_ArrayToPointer)) {
+        // Only add unsized array if there actually is a pointer.
+        return false;        
+      } else {
+        Result.addUnsizedArray(Info, E, AT->getElementType());
+      }
+    }
     return true;
   }
 



More information about the cfe-commits mailing list