[llvm] Add clang::lifetimebound annotation to StringRef constructors. (PR #113878)

Haojian Wu via llvm-commits llvm-commits at lists.llvm.org
Mon Oct 28 01:02:43 PDT 2024


https://github.com/hokein created https://github.com/llvm/llvm-project/pull/113878

Adding the lifetimebound annotation to the ArrayRef's array constructor can enable us to detect the following use-after-free issues:

```
llvm::StringRef TestZoneName() {
   char test[] = "foo"; // oops, missing static
   return test; // use-after-free.
}
```

See #113533

>From 69ac50c26da80166aef3da7f9eb1aa90f5c69fb1 Mon Sep 17 00:00:00 2001
From: Haojian Wu <hokein.wu at gmail.com>
Date: Mon, 28 Oct 2024 08:44:33 +0100
Subject: [PATCH] Add clang::lifetimebound annotation to StringRef
 constructors.

---
 llvm/include/llvm/ADT/StringRef.h | 5 +++--
 1 file changed, 3 insertions(+), 2 deletions(-)

diff --git a/llvm/include/llvm/ADT/StringRef.h b/llvm/include/llvm/ADT/StringRef.h
index f879bbf7164fd6..0dcd4d90086eff 100644
--- a/llvm/include/llvm/ADT/StringRef.h
+++ b/llvm/include/llvm/ADT/StringRef.h
@@ -81,7 +81,7 @@ namespace llvm {
     StringRef(std::nullptr_t) = delete;
 
     /// Construct a string ref from a cstring.
-    /*implicit*/ constexpr StringRef(const char *Str)
+    /*implicit*/ constexpr StringRef(const char *Str LLVM_LIFETIME_BOUND)
         : View(Str, Str ?
     // GCC 7 doesn't have constexpr char_traits. Fall back to __builtin_strlen.
 #if defined(_GLIBCXX_RELEASE) && _GLIBCXX_RELEASE < 8
@@ -93,7 +93,8 @@ namespace llvm {
     }
 
     /// Construct a string ref from a pointer and length.
-    /*implicit*/ constexpr StringRef(const char *data, size_t length)
+    /*implicit*/ constexpr StringRef(const char *data LLVM_LIFETIME_BOUND,
+                                     size_t length)
         : View(data, length) {}
 
     /// Construct a string ref from an std::string.



More information about the llvm-commits mailing list