[clang] [Wunsafe-buffer-usage] Turn off unsafe-buffer warning for methods annotated with clang::unsafe_buffer_usage attribute (PR #125671)

Malavika Samak via cfe-commits cfe-commits at lists.llvm.org
Mon Feb 24 10:02:59 PST 2025


================
@@ -245,3 +243,56 @@ struct AggregateViaDefaultInit {
 void testAggregateViaDefaultInit() {
     AggregateViaDefaultInit A;
 };
+
+struct A {
+  int arr[2];
+
+  [[clang::unsafe_buffer_usage]]
+  int *ptr;
+};
+
+namespace std{
+  template <typename T> class span {
+
+   T *elements;
+
+   public:
+
+   constexpr span(T *, unsigned){}
+
+   template<class Begin, class End>
+   constexpr span(Begin first, End last){}
+
+   constexpr T* data() const noexcept {
+     return elements;
+   }
+ };
+}
+
+[[clang::unsafe_buffer_usage]]
+void check_no_warnings(unsigned idx) {
+  int *arr = new int[20];
+
+  int k = arr[idx]; // no-warning
+
+  std::span<int> sp = {arr, 20}; // no-warning
+  A *ptr = reinterpret_cast<A*> (sp.data()); // no-warning
+  A a;
+  a.ptr = arr; // no-warning
+}
+
+[[clang::unsafe_buffer_usage]]
+void check_no_warning_variadic(unsigned idx, int arr[20], ...) {
+  int k = arr[idx]; // no-warning
+
+  std::span<int> sp = {arr, 20}; // no-warning
+  A *ptr = reinterpret_cast<A*> (sp.data()); // no-warning
+  A a;
+  a.ptr = arr; // no-warning
+}
+
+void invoke_methods() {
+  int array[20];
+  check_no_warnings(30); //expected-warning{{function introduces unsafe buffer manipulation}}
----------------
malavikasamak wrote:

The warning should be emitted at the call site, as this gives the caller an opportunity to switch to a safe API. This was the main reason behind designing this attribute for methods, so the callers can be pushed to switch to safer alternatives. However, warning at each unsafe operation within a method that the user has already identified as unsafe is redundant.

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


More information about the cfe-commits mailing list