[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 13:53:50 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:
Side note: Given the above I expected pointer arithmetic on a function pointer to be forbidden but it's not...
```c
typedef void(fn_ty)(int);
typedef void(*fn_ptr_ty)(int);
void test(fn_ty* fn) {
fn(5); // ok
// WHAT!?: How can pointer arithmetic be possible when the size of
// the function isn't a defined thing...
//
// Turns out clang codegens this as if `sizeof(*fn) == 1`
_Static_assert(sizeof(*fn) == 1, "oh boy...we're in for a wild ride");
++fn;
// Let's jump somewhere into the function that's 1 byte along from the start.
// what could possibly go wrong!?
fn(5); // CRASH
return;
}
```
It's fine to do pointer arithmetic on an array of function pointers though
```c
typedef void(fn_ty)(int);
typedef void(*fn_ptr_ty)(int);
void do_something(int i) { printf("hello %d\n", i);}
void do_something2(int i) { printf("hello2 %d\n", i);}
fn_ptr_ty Funcs[] = { do_something, do_something2};
void test2(fn_ty** fn) {
// fn == do_something
(*fn)(5);
++fn;
// Now fn == do_something2
(*fn)(5);
return;
}
int main(void) {
test2(Funcs);
return 0;
}
```
https://github.com/llvm/llvm-project/pull/90786
More information about the cfe-commits
mailing list