[clang] [clang][bytecode] Check strlen element size (PR #181333)

via cfe-commits cfe-commits at lists.llvm.org
Fri Feb 13 00:45:44 PST 2026


llvmbot wrote:


<!--LLVM PR SUMMARY COMMENT-->

@llvm/pr-subscribers-clang

Author: Timm Baeder (tbaederr)

<details>
<summary>Changes</summary>

We're otherwise running into an assertion later, so do the check early.

---
Full diff: https://github.com/llvm/llvm-project/pull/181333.diff


2 Files Affected:

- (modified) clang/lib/AST/ByteCode/InterpBuiltin.cpp (+2) 
- (modified) clang/test/AST/ByteCode/builtin-functions.cpp (+4-1) 


``````````diff
diff --git a/clang/lib/AST/ByteCode/InterpBuiltin.cpp b/clang/lib/AST/ByteCode/InterpBuiltin.cpp
index 2f86877d31ffb..f14b390831722 100644
--- a/clang/lib/AST/ByteCode/InterpBuiltin.cpp
+++ b/clang/lib/AST/ByteCode/InterpBuiltin.cpp
@@ -365,6 +365,8 @@ static bool interp__builtin_strlen(InterpState &S, CodePtr OpPC,
 
   assert(StrPtr.getFieldDesc()->isPrimitiveArray());
   unsigned ElemSize = StrPtr.getFieldDesc()->getElemSize();
+  if (ElemSize != 1 && ElemSize != 2 && ElemSize != 4)
+    return Invalid(S, OpPC);
 
   if (ID == Builtin::BI__builtin_wcslen || ID == Builtin::BIwcslen) {
     const ASTContext &AC = S.getASTContext();
diff --git a/clang/test/AST/ByteCode/builtin-functions.cpp b/clang/test/AST/ByteCode/builtin-functions.cpp
index 77ba9ca4ce05c..3843774188fa4 100644
--- a/clang/test/AST/ByteCode/builtin-functions.cpp
+++ b/clang/test/AST/ByteCode/builtin-functions.cpp
@@ -21,6 +21,7 @@
 #error "huh?"
 #endif
 
+#define fold(x) (__builtin_constant_p(0) ? (x) : (x))
 
 inline constexpr void* operator new(__SIZE_TYPE__, void* p) noexcept { return p; }
 namespace std {
@@ -229,6 +230,9 @@ constexpr const char *a = "foo\0quux";
 
   int arr[3]; // both-note {{here}}
   int wk = arr[wcslen(L"hello")]; // both-warning {{array index 5}}
+
+  const long long longArray[] = {'b'};
+  constexpr int m = __builtin_strlen(fold((char *)longArray)); // both-error {{must be initialized by a constant expression}}
 }
 
 namespace nan {
@@ -1499,7 +1503,6 @@ namespace BuiltinMemcpy {
   }
   static_assert(memmoveOverlapping());
 
-#define fold(x) (__builtin_constant_p(0) ? (x) : (x))
   static_assert(__builtin_memcpy(&global, fold((wchar_t*)123), sizeof(wchar_t))); // both-error {{not an integral constant expression}} \
                                                                                   // both-note {{source of 'memcpy' is (void *)123}}
   static_assert(__builtin_memcpy(fold(reinterpret_cast<wchar_t*>(123)), &global, sizeof(wchar_t))); // both-error {{not an integral constant expression}} \

``````````

</details>


https://github.com/llvm/llvm-project/pull/181333


More information about the cfe-commits mailing list