[libc-commits] [libc] [libc] add basic lifetime annotations for support data structures (PR #145933)

Michael Jones via libc-commits libc-commits at lists.llvm.org
Fri Oct 17 09:56:06 PDT 2025


================
@@ -91,4 +91,84 @@ LIBC_THREAD_MODE_EXTERNAL.
 #define LIBC_NO_SANITIZE_OOB_ACCESS
 #endif
 
+// LIBC_LIFETIME_BOUND indicates that a function parameter's lifetime is tied
+// to the return value. This helps compilers detect use-after-free bugs.
+//
+// Example usage:
+//   const T &get_value(const Container &c LIBC_LIFETIME_BOUND,
+///                      const T &default_val LIBC_LIFETIME_BOUND);
+//   // Warns if temporary Container or default_val is bound to the result
+//
+// For member functions, apply after the function signature:
+//   const char *data() const LIBC_LIFETIME_BOUND;
+//   // The returned pointer should not outlive '*this'
+#if __has_cpp_attribute(clang::lifetimebound)
+#define LIBC_LIFETIME_BOUND [[clang::lifetimebound]]
+#elif __has_cpp_attribute(msvc::lifetimebound)
+#define LIBC_LIFETIME_BOUND [[msvc::lifetimebound]]
+#elif __has_cpp_attribute(lifetimebound)
+#define LIBC_LIFETIME_BOUND [[lifetimebound]]
+#else
+#define LIBC_LIFETIME_BOUND
+#endif
+
+// LIBC_LIFETIME_CAPTURE_BY(X) indicates that parameter X captures/stores a
+// reference to the annotated parameter. Warns if temporaries are passed.
+//
+// Example usage:
+//   void add_to_set(std::string_view a LIBC_LIFETIME_CAPTURE_BY(s),
+//                   std::set<std::string_view>& s) {
+//     s.insert(a); // 's' now holds a reference to 'a'
+//   }
+//   // Warns: add_to_set(std::string(), s); // temporary captured by 's'
----------------
michaelrj-google wrote:

nit: either remove the `std` or change to `cpp` since we don't use `std::string_view` in libc.

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


More information about the libc-commits mailing list