[clang] [Bounds-Safety] Add sized_by, counted_by_or_null & sized_by_or_null (PR #93231)

Dan Liew via cfe-commits cfe-commits at lists.llvm.org
Fri May 24 15:05:12 PDT 2024


================
@@ -8641,22 +8641,33 @@ enum class CountedByInvalidPointeeTypeKind {
   VALID,
 };
 
-static bool CheckCountedByAttrOnField(
-    Sema &S, FieldDecl *FD, Expr *E,
-    llvm::SmallVectorImpl<TypeCoupledDeclRefInfo> &Decls) {
+static bool
+CheckCountedByAttrOnField(Sema &S, FieldDecl *FD, Expr *E,
+                          llvm::SmallVectorImpl<TypeCoupledDeclRefInfo> &Decls,
+                          bool CountInBytes, bool OrNull) {
   // Check the context the attribute is used in
 
+  unsigned Kind = CountInBytes;
+  if (OrNull)
+    Kind += 2;
+
   if (FD->getParent()->isUnion()) {
     S.Diag(FD->getBeginLoc(), diag::err_counted_by_attr_in_union)
-        << FD->getSourceRange();
+        << Kind << FD->getSourceRange();
     return true;
   }
 
   const auto FieldTy = FD->getType();
+  if (FieldTy->isArrayType() && (CountInBytes || OrNull)) {
+    S.Diag(FD->getBeginLoc(),
+           diag::err_counted_by_attr_not_on_ptr_or_flexible_array_member)
----------------
delcypher wrote:

> > The OrNull case probably deserves its own special diagnostic because in that case the diagnostic should explain that they cannot use the attribute on arrays and that they need to use __counted_by instead.
> 
> That is also true for `CountInBytes`. But I agree that it would be good for the diagnostic to suggest `counted_by`.

Hmm looking at it more closely for the `err_counted_by_attr_not_on_ptr_or_flexible_array_member` means the diagnostic output for

```
struct Test {
  int count;
  int fma[] __counted_by_or_null(count)
}
```

would look something like

```
counted_by_or_null only applies to pointers
```

i.e. mentioning flexible array members is dropped (I initially thought it wasn't). So actually I guess this is fine. Suggesting the right attribute would be an extra bonus.  If you don't want to do it now file an issue (tagged with clang:bounds-safety).

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


More information about the cfe-commits mailing list