[clang] [attributes][-Wunsafe-buffer-usage] Support adding unsafe_buffer_usage attribute to struct fields (PR #101585)

Malavika Samak via cfe-commits cfe-commits at lists.llvm.org
Fri Aug 2 15:50:19 PDT 2024


================
@@ -0,0 +1,113 @@
+// RUN: %clang_cc1 -std=c++20 -Wunsafe-buffer-usage \
+// RUN:            -fsafe-buffer-usage-suggestions -verify %s
+
+using size_t = __typeof(sizeof(int));
+
+namespace std {
+  class type_info;
+  class bad_cast;
+  class bad_typeid;
+
+  template <typename T> class span {
+
+  private:
+    T *elements;
+    size_t size_;
+
+  public:
+    span(T *, size_t){}
+
+    constexpr T* data() const noexcept {
+      return elements;
+    }
+
+    constexpr size_t size() const noexcept {
+      return size_;
+    }
+
+  };
+}
+
+struct A {
+    [[clang::unsafe_buffer_usage]]
+    int *ptr;
+
+    size_t sz;
+};
+
+struct B {
+   A a;
+ 
+   [[clang::unsafe_buffer_usage]]
+   int buf[];
+};
+
+union Union {
+  [[clang::unsafe_buffer_usage]]
+  int *ptr1;
+
+  int ptr2;
+};
+
+struct C {
+  Union ptr; 
+};
+
+struct D { 
+  [[clang::unsafe_buffer_usage]]
+  int *ptr, *ptr2;
+
+  [[clang::unsafe_buffer_usage]]
+  int buf[10];
+ 
+  size_t sz;
+  
+};
+
+void foo(int *ptr);
+
+void foo_safe(std::span<int> sp);
+
+void test_attribute_union(C c) {
+  int *p = c.ptr.ptr1; //expected-warning{{field ptr1 prone to unsafe buffer manipulation}}
+
+  // TODO: Warn here about the field
----------------
malavikasamak wrote:

This could be a potentially be added to this patch. The question is if the attribute is added to a member of a Union field, should we warn when other fields of the said union are accessed. I think we probably should, as it is referring to the same memory. Wanted to know if it's something we are interested to do as part of this patch or a future patch.

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


More information about the cfe-commits mailing list