[clang] [BoundsSafety] Allow 'counted_by' attribute on pointers in structs in C (PR #90786)

Dan Liew via cfe-commits cfe-commits at lists.llvm.org
Fri May 3 12:48:06 PDT 2024


================
@@ -6534,6 +6536,15 @@ def err_counted_by_attr_refer_to_union : Error<
   "'counted_by' argument cannot refer to a union member">;
 def note_flexible_array_counted_by_attr_field : Note<
   "field %0 declared here">;
+def err_counted_by_attr_pointee_unknown_size : Error<
+  "'counted_by' cannot be applied a pointer with pointee with unknown size "
+  "because %0 is %select{"
+    "an incomplete type|"  // CountedByInvalidPointeeTypeKind::INCOMPLETE
+    "a sizeless type|"     // CountedByInvalidPointeeTypeKind::SIZELESS
+    "a function type|"     // CountedByInvalidPointeeTypeKind::FUNCTION
----------------
delcypher wrote:

@bwendling I was also confused by this initially. A "function type" and "function pointer type" are **different**. A function type doesn't have a size so we have to forbid it, but a function pointer does have a size (it's the size of a pointer).

Hopefully these examples illustrate the problem:

```c
#define __counted_by(f)  __attribute__((counted_by(f)))

typedef void(fn_ty)(int);
typedef void(*fn_ptr_ty)(int);

struct a {
    int count;
    // Buffer of functions is invalid. A "function" has no size
    fn_ty* buffer __counted_by(count);
    fn_ptr_ty buffer2 __counted_by(count);
};

struct b {
    int count;
    // Valid: A buffer of function pointers is allowed
    fn_ty** buffer __counted_by(count);
    fn_ptr_ty* buffer2 __counted_by(count);
};
```

A similar thing exists for arrays. If you write this

```c
struct c {
    fn_ty Arr[];
};
```

this produces the following error:

```
error: 'Arr' declared as array of functions of type 'fn_ty' (aka 'void (int)')
   22 |     fn_ty Arr[];
      |              ^
```

However these two struct definitions are allowed by clang:

```c
struct d {
    fn_ty* Arr[];
};

struct e {
    fn_ptr_ty Arr2[];
};
```


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


More information about the cfe-commits mailing list