================
@@ -6835,6 +6837,31 @@ the proper solution would be to create a different 
function (possibly
 an overload of ``baz()``) that accepts a safe container like ``bar()``,
 and then use the attribute on the original ``baz()`` to help the users
 update their code to use the new function.
+
+Attribute attached to fields:
+
+The attribute should only be attached to struct fields, if the fields can not 
be
+updated to a safe type with bounds check, such as std::span. In other words, 
the
+buffers prone to unsafe accesses should always be updated to use safe 
containers/views
+and attaching the attribute must be last resort when such an update is 
infeasible.
+
+The attribute can be placed on individual fields or a set of them as shown 
below.
+.. code-block:: c++
+
+  struct A {
+    [[clang::unsafe_buffer_usage]]
+    int *ptr1;
+
+    [[clang::unsafe_buffer_usage]]
+    int *ptr2, buf[10];
+
+    [[clang::unsafe_buffer_usage]]
+    size_t sz;
+  };
+
+Here, every read/write to the fields ptr1, ptr2, buf and sz will trigger a 
warning that the
+field has been explcitly marked as unsafe due to unsafe-buffer operations.
+
----------------
haoNoQ wrote:
I feel the need to add something constructive here, to give people a way to 
eliminate the warning.

> "Together with adding the attribute, it is recommended to provide a safe way 
> of accessing these structs. Under our assumption that the fields cannot be 
> edited, or even made private, for compatibility reasons, one possible 
> solution is to provide safe `span`-based accessor methods to these fields, 
> then use the attribute to encourage users to use those methods, without 
> breaking compatibility if they don't: 
> ```
> struct A {
>     [[clang::unsafe_buffer_usage]]
>     int *ptr;
>     [[clang::unsafe_buffer_usage]]
>     size_t sz;
>
>     std::span<int> getPtrAsSpan() {
>         #pragma clang unsafe_buffer_usage begin
>         return std::span{ptr, sz};
>         #pragma clang unsafe_buffer_usage end
>     }
>
>     void setPtrFromSpan(std::span<int> sp) {
>         #pragma clang unsafe_buffer_usage begin
>         ptr = sp.data();
>         sz = sp.size();
>         #pragma clang unsafe_buffer_usage begin
>     }
> }
> ```
> ".

https://github.com/llvm/llvm-project/pull/101585
_______________________________________________
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits

Reply via email to