Skip to content

regex: Constrain the lifetime of results that borrow text - #260

Merged
copybara-service[bot] merged 2 commits into
google:mainfrom
dhivadhiva:regex-text-lifetime-bound
Nov 11, 2026
Merged

copybara-service[bot] merged 2 commits into
google:mainfrom
dhivadhiva:regex-text-lifetime-bound

Conversation

@dhivadhiva

@dhivadhiva dhivadhiva commented Nov 10, 2026 •

Copy link
Copy Markdown
Contributor

Follow-up to #257, from the review discussion there.

Find(), FindCaptures(), FindAll(), FindAllCaptures() and both Split() overloads return objects that hold a slice of text on the Rust side (Match<'h>, Captures<'h> and the iterators). #257 bound the ranges to the Regex, but text still had no annotation, so passing a temporary string compiled silently and dangled:

std::optional<Match> m = re.Find(absl::StrCat(a, b));      // dangled
for (absl::string_view p : re.Split(GetLine())) { ... }    // dangled before C++23

This marks text ABSL_ATTRIBUTE_LIFETIME_BOUND on all six. Clang reports these through -Wdangling-gsl (the std::string to string_view conversion), which is on by default.

  • Not affected: a string_view argument, including one returned by value (such as a string_view accessor), a string literal, a const std::string&, and using the result within the full-expression. Find() on a temporary Regex also stays fine, because a Match borrows the text, not the Regex.
  • Not diagnosed, documented on Find(): taking AsStr() from the Match of a temporary in the same expression, as in re.Find(GetText())->AsStr(), however the optional is unwrapped (->, * or .value()). Match is itself a view of text, so Match::AsStr() is deliberately neither lifetime-bound nor deleted for rvalues: re.Find(text)->AsStr() must keep working.

No ref-qualifiers or deleted overloads change, so existing callers keep compiling unless they hit one of the cases above.

Testing

Full CMake build (Crubit f144a4f, Rust nightly-2026-11-07, clang 21.1.8):

  • regex, regex_example and regex_benchmark build, and regex_example runs.
  • main.cc, regex.cc and regex_benchmark.cc compile with -Werror=dangling -Werror=dangling-gsl.
  • The clang -verify test from regex: Constrain the lifetime of Regex::AsStr(), Match::Inner() and RegexFlagWithOptions::pattern() #257, extended with 10 cases for text (below), passes on this branch. On main it fails on exactly those 10.
    • Rejected now: a Match, Captures or range kept from Find(), FindCaptures() or FindAll() of a temporary std::string, including std::string_view(Text()) and Text() + "x"; and a range-for over FindAll(), FindAllCaptures(), either Split() overload, or StatusOr<Regex>->Split() of a temporary.
    • Still compiles: string_views returned by value, absl::string_view(s), sv.substr(1), const char*, string literals, const std::string& and string_view accessors, full-expression use, and Regex::Compile(p)->Find(s).
  • In C++23 mode, Clang stays quiet on the range-for cases, which is correct since P2718 extends the temporary, and still flags the ones kept in a local.
lifetime_verify.cc
// clang -verify test for the regex lifetime annotations: the ones from
// google/safe-bindings#257, plus the `text` follow-up at the end.
//   clang++ -std=gnu++20 -fsyntax-only -Xclang -verify \
//     -Xclang -verify-ignore-unexpected=note <include flags>
#include <cstddef>
#include <cstdint>
#include <optional>
#include <string>

#include "absl/flags/flag.h"
#include "absl/strings/string_view.h"
#include "regex.h"
#include "regex_flag.h"

using security::regex::Captures;
using security::regex::Match;
using security::regex::Regex;
using security::regex::RegexFlag;
using security::regex::RegexListFlag;

ABSL_FLAG(RegexFlag, re, RegexFlag::OrDie("a+"), "");
ABSL_FLAG(RegexListFlag, re_list, RegexListFlag::OrDie({"a", "b"}), "");

// ---- Already in the PR: AsStr(), Inner(), pattern() -----------------------

void DanglingAccessors() {
  absl::string_view a = Regex::Compile("a+")->AsStr();  // expected-warning {{temporary whose address is used as value of local variable 'a' will be destroyed at the end of the full-expression}}
  absl::string_view b = (*Regex::Compile("a+")).AsStr();  // expected-error {{call to deleted member function 'AsStr'}}
  absl::string_view c = Regex::Compile("a+").value().AsStr();  // expected-error {{call to deleted member function 'AsStr'}}
  auto re = Regex::Compile("a+");
  const auto& d = (*re->Find("aa")).Inner();  // expected-error {{call to deleted member function 'Inner'}}
  absl::string_view e = absl::GetFlag(FLAGS_re).pattern();  // expected-warning {{temporary whose address is used as value of local variable 'e' will be destroyed at the end of the full-expression}}
  (void)a; (void)b; (void)c; (void)d; (void)e;
}

// ---- Review: flag accessors -----------------------------------------------

void DanglingFlags() {
  // The header's own "BAD!" example.
  const Regex& a = *absl::GetFlag(FLAGS_re);  // expected-warning {{temporary bound to local reference 'a' will be destroyed at the end of the full-expression}}
  // The reviewer's example: gets past AsStr() const&& = delete via operator->.
  absl::string_view b = absl::GetFlag(FLAGS_re)->AsStr();  // expected-warning {{temporary whose address is used as value of local variable 'b' will be destroyed at the end of the full-expression}}
  const Regex* c = absl::GetFlag(FLAGS_re).get();  // expected-warning {{temporary whose address is used as value of local variable 'c' will be destroyed at the end of the full-expression}}
  auto d = absl::GetFlag(FLAGS_re_list).begin();  // expected-warning {{temporary whose address is used as value of local variable 'd' will be destroyed at the end of the full-expression}}
  auto e = absl::GetFlag(FLAGS_re_list).end();  // expected-warning {{temporary whose address is used as value of local variable 'e' will be destroyed at the end of the full-expression}}
  (void)a; (void)b; (void)c; (void)d; (void)e;
}

// ---- Review: ranges that borrow *this -------------------------------------

void DanglingRanges() {
  // Through absl::StatusOr::operator->.
  auto a = Regex::Compile("a+")->FindAll("aa");  // expected-warning {{temporary whose address is used as value of local variable 'a' will be destroyed at the end of the full-expression}}
  // The reviewer's example: pre-C++23 range-for destroys the Regex first.
  for (auto n : Regex::Compile("(a)")->CaptureNames()) (void)n;  // expected-warning {{temporary implicitly bound to local reference will be destroyed at the end of the full-expression}}
  for (Match m : Regex::Compile("a+")->FindAll("aa")) (void)m;  // expected-warning {{temporary implicitly bound to local reference will be destroyed at the end of the full-expression}}
  for (auto c : Regex::Compile("(a)")->FindAllCaptures("a")) (void)c;  // expected-warning {{temporary implicitly bound to local reference will be destroyed at the end of the full-expression}}
  for (auto p : Regex::Compile(",")->Split("a,b")) (void)p;  // expected-warning {{temporary implicitly bound to local reference will be destroyed at the end of the full-expression}}
  for (auto p : Regex::Compile(",")->Split("a,b", 1)) (void)p;  // expected-warning {{temporary implicitly bound to local reference will be destroyed at the end of the full-expression}}

  // Rvalue Regex / Captures: deleted const&& overloads.
  auto b = (*Regex::Compile("(a)")).CaptureNames();  // expected-error {{call to deleted member function 'CaptureNames'}}
  auto c = Regex::Compile("a+").value().FindAll("aa");  // expected-error {{call to deleted member function 'FindAll'}}
  auto d = (*Regex::Compile("(a)")).FindAllCaptures("a");  // expected-error {{call to deleted member function 'FindAllCaptures'}}
  auto e = (*Regex::Compile(",")).Split("a,b");  // expected-error {{call to deleted member function 'Split'}}
  auto f = (*Regex::Compile(",")).Split("a,b", 1);  // expected-error {{call to deleted member function 'Split'}}
  auto re = Regex::Compile("(a)");
  for (auto m : (*re->FindCaptures("a")).GetAll()) (void)m;  // expected-error {{call to deleted member function 'GetAll'}}
  auto g = re->FindCaptures("a").value().GetAll();  // expected-error {{call to deleted member function 'GetAll'}}
}

// ---- Still compiles --------------------------------------------------------

template <typename R>
size_t Count(R&& r) {
  size_t n = 0;
  for (auto&& x : r) { (void)x; ++n; }
  return n;
}

void StillAllowed(const Regex& lv, const RegexFlag& flag) {
  // Lvalues are unaffected.
  absl::string_view a = lv.AsStr();
  for (Match m : lv.FindAll("aa")) (void)m;
  for (auto n : lv.CaptureNames()) (void)n;
  auto kept = lv.Split("a,b");
  for (auto p : kept) (void)p;
  std::optional<Captures> caps = lv.FindCaptures("a");
  for (auto m : caps->GetAll()) (void)m;
  const Regex& b = *flag;
  absl::string_view c = flag->AsStr();
  // Consuming inside the full-expression is fine.
  std::string d(Regex::Compile("a+")->AsStr());
  size_t n1 = Count(Regex::Compile("a")->FindAll("aaa"));
  size_t n2 = Count(Regex::Compile(",")->Split("a,b,c", 2));
  bool m1 = absl::GetFlag(FLAGS_re)->IsMatch("aa");
  bool m2 = (*absl::GetFlag(FLAGS_re)).IsMatch("aa");
  std::string e(absl::GetFlag(FLAGS_re)->AsStr());
  std::string f(absl::GetFlag(FLAGS_re).pattern());
  // Range-for keeps the flag copy alive for the whole loop.
  for (const auto& r : absl::GetFlag(FLAGS_re_list)) (void)r->IsMatch("a");
  // Arg's numeric parsing goes through Match::Inner() on an lvalue.
  int32_t i = 0;
  std::optional<Match> m = lv.Find("12");
  bool ok = security::regex::internal::ParseNumeric<10>(*m, &i);
  // Unparsing goes through pattern() / begin() / end() on lvalues.
  std::string u1 = absl::UnparseFlag(absl::GetFlag(FLAGS_re));
  std::string u2 = absl::UnparseFlag(absl::GetFlag(FLAGS_re_list));
  (void)a; (void)b; (void)c; (void)n1; (void)n2; (void)m1; (void)m2; (void)ok;
}

// Known gap: std::optional::operator-> is not annotated, so these still
// compile. The GetAll() case is documented on Captures::GetAll().
void KnownGap(const Regex& re) {
  const auto& inner = re.Find("aa")->Inner();
  auto all = re.FindCaptures("a")->GetAll();
  (void)inner;
}

// ---- Follow-up: the `text` borrow -----------------------------------------

std::string Text();
absl::string_view View();
std::string_view StdView();
const char* CStr();
struct Msg {
  const std::string& field() const;
  absl::string_view view_field() const;
};

void DanglingText(const Regex& re) {
  std::optional<Match> a = re.Find(Text());  // expected-warning {{object backing the pointer will be destroyed at the end of the full-expression}}
  std::optional<Captures> b = re.FindCaptures(Text());  // expected-warning {{object backing the pointer will be destroyed at the end of the full-expression}}
  auto c = re.FindAll(Text());  // expected-warning {{object backing the pointer will be destroyed at the end of the full-expression}}
  // Pre-C++23 range-for over a temporary string.
  for (Match m : re.FindAll(Text())) (void)m;  // expected-warning {{object backing the pointer will be destroyed at the end of the full-expression}}
  for (auto x : re.FindAllCaptures(Text())) (void)x;  // expected-warning {{object backing the pointer will be destroyed at the end of the full-expression}}
  for (auto p : re.Split(Text())) (void)p;  // expected-warning {{object backing the pointer will be destroyed at the end of the full-expression}}
  for (auto p : re.Split(Text(), 2)) (void)p;  // expected-warning {{object backing the pointer will be destroyed at the end of the full-expression}}
  // Explicit view of a temporary, and a concatenation.
  std::optional<Match> d = re.Find(std::string_view(Text()));  // expected-warning {{object backing the pointer will be destroyed at the end of the full-expression}}
  std::optional<Match> e = re.Find(Text() + "x");  // expected-warning {{object backing the pointer will be destroyed at the end of the full-expression}}
  // Through absl::StatusOr::operator->, as in the header's example.
  auto sre = Regex::Compile(",");
  for (auto p : sre->Split(absl::StrCat("a", ",b"))) (void)p;  // expected-warning {{object backing the pointer will be destroyed at the end of the full-expression}}
  (void)a; (void)b; (void)d; (void)e;
}

void TextStillAllowed(const Regex& re, const std::string& s,
                      absl::string_view sv, const Msg& msg) {
  // Views, including ones returned by value, are not temporaries that own
  // the text.
  std::optional<Match> a = re.Find(View());
  std::optional<Match> b = re.Find(StdView());
  std::optional<Match> c = re.Find(absl::string_view(s));
  std::optional<Match> d = re.Find(sv.substr(1));
  std::optional<Match> e = re.Find(CStr());
  std::optional<Match> f = re.Find("literal");
  std::optional<Match> g = re.Find(msg.field());
  std::optional<Captures> h = re.FindCaptures(msg.view_field());
  for (Match m : re.FindAll(View())) (void)m;
  for (auto p : re.Split(msg.view_field(), 2)) (void)p;
  auto i = re.FindAll(s);
  // Consuming within the full-expression.
  bool j = re.Find(Text()).has_value();
  std::string k(re.Find(Text())->AsStr());
  size_t n = Count(re.Split(Text()));
  // A Match borrows the text, not the Regex, so a temporary Regex is fine.
  std::optional<Match> l = Regex::Compile("a")->Find(s);
  (void)a; (void)b; (void)c; (void)d; (void)e; (void)f; (void)g; (void)h;
  (void)j; (void)n; (void)l;
}

// Known gap, documented on Regex::Find(): Match::AsStr() is neither
// lifetime-bound nor deleted for rvalues (Match is a view of `text`), so
// none of the ways to unwrap the optional is diagnosed.
void TextKnownGap(const Regex& re) {
  absl::string_view s = re.Find(Text())->AsStr();
  absl::string_view t = (*re.Find(Text())).AsStr();
  absl::string_view u = re.Find(Text()).value().AsStr();
  (void)s; (void)t; (void)u;
}

Find(), FindCaptures(), FindAll(), FindAllCaptures() and both Split()
overloads return objects that hold a slice of `text` on the Rust side
(Match<'h>, Captures<'h> and the iterators), but `text` had no lifetime
annotation. Passing a temporary string compiled silently and dangled:

    std::optional<Match> m = re.Find(absl::StrCat(a, b));
    for (absl::string_view p : re.Split(GetLine())) { ... }  // pre-C++23

Mark `text` ABSL_ATTRIBUTE_LIFETIME_BOUND on all six. Clang now rejects
both (-Wdangling-gsl, through the std::string to string_view
conversion). A string_view argument, including one returned by value, a
string literal or a const std::string& is not affected, and neither is
using the result within the full-expression.

Not diagnosed, and documented on Find(): reaching the Match through
std::optional::operator->, as in re.Find(GetText())->AsStr().

Follow-up to the review of google#257.

@vabr-g vabr-g left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Looks good, just one minor nit.

Comment thread regex/regex.h Resolved
The note on Find() put re.Find(temp)->AsStr() going undiagnosed down to
std::optional::operator->. The actual reason is Match::AsStr(): Match is
itself a view of `text`, so AsStr() is deliberately neither
ABSL_ATTRIBUTE_LIFETIME_BOUND nor deleted for rvalues, since
re.Find(text)->AsStr() must keep working. The case is therefore
undiagnosed however the optional is unwrapped: ->, * or .value().

@vabr-g vabr-g left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks!

@copybara-service
copybara-service Bot merged commit a9165af into google:main Nov 11, 2026
12 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants