Skip to content

Add support for the lifetimebound attribute - #9060

Open
pfultz2 wants to merge 10 commits into
cppcheck-opensource:mainfrom
pfultz2:clang-lifetimebound-attribute
Open

pfultz2 wants to merge 10 commits into
cppcheck-opensource:mainfrom
pfultz2:clang-lifetimebound-attribute

Conversation

@pfultz2

@pfultz2 pfultz2 commented Nov 23, 2026

Copy link
Copy Markdown
Collaborator

The lifetime analysis now uses [[clang::lifetimebound]], [[msvc::lifetimebound]] and __attribute__((lifetimebound)) on function parameters, constructor parameters and member functions. So we can find dangling pointers and invalidated iterators when the body of the called function is not available.

The attribute doesn't say whether the result refers to the object itself or to its contents(ie a pointer to the vector vs a pointer to its elements). By default we assume the object itself, so the result is checked for dangling but not for container invalidation in order to avoid false positives. We only treat it as the contents when the return type, the argument or the function body shows it. This is described in man/lifetimebound.md.

Also, getLifetimeTokens now tracks whether the expression is the object itself or a part of it, which changes some results without the attribute. A reference to the container(const std::vector<int>& r = v;) is no longer reported by invalidContainerReference after a push_back, and std::string_view sv = s; and &*std::begin(v) are now reported by invalidContainer. There are trac tickets for these issues.

There are still false negatives when the return type doesn't show what the result refers to, such as a struct that stores a pointer to the elements. The interior borrows proposed in llvm/llvm-project#236200 could fix this in the future.

@dmcppcheck

Copy link
Copy Markdown
Contributor

There should probably be a trac ticket for this PR. Please create it, or ask us to create it. Then the PR title should be updated.

@dmcppcheck dmcppcheck left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

AI review

I found two new problems; nobody has raised either one yet.

  1. False positive on owning results (most important). The lifetimebound path never checks whether the result type can borrow at all. Owning types like std::string or std::vector<int> get lifetime values anyway. So std::string u = upper(s); s += "b"; return u; gives both returnDanglingLifetime and invalidContainer on u, even though u is an independent copy. Code without the attribute does not do this, because it goes through isLifetimeBorrowed on the returned expression.
  2. Regression in constructors (false negative). If one constructor parameter has the attribute, the existing hasBorrowingVariables heuristic is turned off for all the other parameters. A pointer to a local that is passed to a parameter without the attribute is then no longer reported (base did report it).

Otherwise the implementation behaves as documented. Every example in man/lifetimebound.md gives exactly the output it promises, and I found no crashes.

Comments

# Comment By Where Status
1 Owning results (std::string, std::vector) get lifetimes from lifetimebound arguments AI review lib/valueflow.cpp:2731 🆕 New
2 Attribute on one ctor param disables hasBorrowingVariables for the others AI review lib/valueflow.cpp:2812 🆕 New (false negative)

@pfultz2, please fix, resolve or reply to the open and new comments: #1, #2.
For #2 (false negative), it is enough to create a Trac ticket and link it here. It does not need to be fixed in this PR.

Testing

  • I built cppcheck and testrunner from pr/, and cppcheck from base/.
  • ./testrunner TestAutoVariables TestStl TestBufferOverrun TestSymbolDatabase TestTokenizer TestValueFlow: 1353 tests, 0 failed.
  • I pulled every code block out of man/lifetimebound.md and ran it with --inconclusive --library=std. All results match the expected output in the doc.
  • Other things I tried (all as the doc describes):
    • Attribute spellings: [[clang::lifetimebound]], __attribute__((lifetimebound)) in a C file, and the attribute behind a macro.
    • Placements: trailing return type, operator(), a template function parameter, a temporary argument (danglingTempReference), a default argument, and a function-pointer declaration.
    • Code without the attribute: some invalidContainerReference results changed. Each change matches what the PR description announces.
  • p->get() on a raw pointer is not reported. This matches the existing behaviour for functions with a body, so I did not report it.

False positive: owning return type

#include <string>
#include <string_view>
std::string upper(std::string_view a [[clang::lifetimebound]]);
std::string f1() { std::string s = "a"; std::string u = upper(s); s += "b"; return u; }

pr/cppcheck -q --library=std t6.cpp

4:84: error: Returning object that points to local variable 's' that will be invalid when returning. [returnDanglingLifetime]
4:84: error: Using object that points to local variable 's' that may be invalid. [invalidContainer]

Base: no output. The same happens with std::vector<int> copy(const std::vector<int>& v [[clang::lifetimebound]]); ... return copy(v); → returnDanglingLifetime.

Regression: constructor heuristic is disabled for parameters without the attribute

struct V { V(const int& a [[clang::lifetimebound]], const int* b); const int* a; const int* b; };
V f(const int& x) { int y = 0; return V(x, &y); }
struct W { W(const int& a, const int* b); const int* a; const int* b; };
W g(const int& x) { int y = 0; return W(x, &y); }

cppcheck -q --inconclusive t5.cpp

  • base: reports both line 2 and line 4 (inconclusive: Returning object that points to local variable 'y' ... [returnDanglingLifetime]).
  • PR: reports only line 4. Line 2 is lost because a now has the attribute.

Automated review of 2b2c0a1 by Claude. The pull request was built and tested locally.

Comment thread lib/valueflow.cpp
ls.type = getLifetimeBoundKind(boundArg.relation, isInteriorArgument(boundArg.tok, settings));
return ls.byRef(tok, tokenlist, errorLogger, settings);
}
ls.byValKind = LifetimeBoundByValKind{boundArg.relation, astIsIterator(tok)};

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

AI review

Nothing here (or in getLifetimeBoundRelation) checks whether the result can borrow. The result of a call with a lifetimebound argument gets a lifetime even when its type is an owning container. With std::string upper(std::string_view a [[clang::lifetimebound]]);, the code std::string u = upper(s); s += "b"; return u; gives returnDanglingLifetime and invalidContainer for u, which is an independent copy. std::vector<int> copy(const std::vector<int>& v [[clang::lifetimebound]]) with return copy(v); also gives returnDanglingLifetime. Base reports nothing for either.

The annotation is questionable on such functions, but cppcheck knows that these containers own their data. For the result token, the path without the attribute filters this with isLifetimeBorrowed. Something like if (!ValueFlow::isLifetimeBorrowed(tok, settings)) return false; (or a check for an owned, non-view container) would avoid these false positives.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

If the user is writing a lifetimebound we should respect that even if it looks like an owner. We could look at adding a check to have a warning about an incorrect lifetimebound:

https://trac.cppcheck.net/ticket/15273

Comment thread lib/valueflow.cpp Outdated
ls.byVal(tok, tokenlist, errorLogger, settings);
});
} else if (hasBorrowingVariables(constructor->nestedIn->varlist, args)) {
} else if (!lifetimeBound && hasBorrowingVariables(constructor->nestedIn->varlist, args)) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

AI review

!lifetimeBound turns off the hasBorrowingVariables heuristic for all arguments, not only the bound ones. So adding the attribute to one parameter loses the warnings for the other parameters:

struct V { V(const int& a [[clang::lifetimebound]], const int* b); const int* a; const int* b; };
V f(const int& x) { int y = 0; return V(x, &y); }

With --inconclusive, base reports Returning object that points to local variable 'y' here; the PR reports nothing. The same struct without the attribute is still reported. Consider keeping the heuristic for the arguments that are not lifetimebound.

@dmcppcheck

Copy link
Copy Markdown
Contributor

Test results for commit 2b2c0a1 (tools/test-my-pr.py, main compared to this PR):

Test: http://ec2-16-170-140-253.eu-north-1.compute.amazonaws.com/pr-9060/
packages: 1000
Differing warnings: 60 (+0 -60)
AI review: 50 improvement (http://ec2-16-170-140-253.eu-north-1.compute.amazonaws.com/pr-9060/2026-11-24_00-25-56-2b2c0a14d391-review.txt)
Timing: +0.3% (http://ec2-16-170-140-253.eu-north-1.compute.amazonaws.com/pr-9060/2026-11-24_00-25-56-2b2c0a14d391_timing.html)

Posted automatically by the cppcheck PR test runner. +N: warnings only with this PR, -N: warnings only with main. The AI review is written by Claude and can be wrong.

@dmcppcheck dmcppcheck left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

AI review

I found no new problems.

  • C4 (constructor regression) is fixed. If one constructor parameter has the attribute, the parameters without it still get the inconclusive hasBorrowingVariables lifetimes. Base and PR now give the same warning.
  • C3 (owning results) is moved to a ticket. The false positive on owning results such as std::string u = upper(s) is still there. The author wants to respect the user's annotation and opened https://trac.cppcheck.net/ticket/15273 for a check that warns about a wrong lifetimebound.
  • C1 is still open. The maintainer asked for a Trac ticket for the PR and a matching title, and nobody has answered yet.

In my own tests, every change in results without the attribute was either announced in the PR description or an improvement: a false positive in invalidContainer is gone (const std::vector<int>* q = idv(&v); v.push_back(2); q->size()). I found no crashes on odd attribute placements.

Comments

# Comment By Where Status
1 PR should get a trac ticket and the title should be updated @dmcppcheck general ⚠️ Open
2 Owning results (std::string, std::vector) get lifetimes from lifetimebound arguments AI review lib/valueflow.cpp:2731 🎫 Ticket #15273
3 Attribute on one ctor param disables hasBorrowingVariables for the others AI review lib/valueflow.cpp:2812 ✅ Fixed

@pfultz2, please fix, resolve or reply to the open and new comments: #1.

Testing

Builds

  • make -j8 cppcheck testrunner in pr/ built fine.
  • make -j8 cppcheck in base/ built fine.

Unit tests

  • ./testrunner TestAutoVariables TestStl TestBufferOverrun TestSymbolDatabase TestTokenizer TestValueFlow: 1353 tests, 0 failed.

Earlier review findings, checked again

  • The C4 example, a constructor with one lifetimebound parameter and &y passed to the other one, is reported by the PR again with --inconclusive. The output is the same as base.
  • The C3 example (std::string upper(std::string_view a [[clang::lifetimebound]])) still gives returnDanglingLifetime and invalidContainer. A ticket covers this.

Code without the attribute, PR compared to base
I wrote about 20 dangling and invalidation cases: deref of a pointer to a local, struct members, 2D arrays, v[0], data(), c_str(), iterators, a reference to a vector, and a reference to an element of a vector of vectors.

  • The only difference is that std::vector<int>& r = v; v.push_back(2); return r[0]; is no longer reported. The PR description announces this change.
  • With function bodies that return their argument (id(v.begin()), idp(v.data()), idc(s.c_str())), every true positive is kept.
  • The PR removes a false positive in invalidContainer: const std::vector<int>* q = idv(&v); v.push_back(2); q->size().

Code with the attribute

  • Placements that work:
    • member functions with const &, noexcept, a trailing return type, virtual, operator() and a conversion operator;
    • template functions and members of class templates;
    • a parameter after a non-bound parameter, and a default argument (not tracked, as documented);
    • a parameter of array-reference type int (&a)[3];
    • an rvalue-reference parameter, which gives danglingTempReference.
  • Views and iterators:
    • trim(s) and trim2(s) to std::string_view followed by s += ... give invalidContainer;
    • an iterator passed through nxt(it) followed by push_back gives invalidContainer;
    • P(&x) gives returnDanglingLifetime.
  • No false positives:
    • for results of type int;
    • for arguments passed through a raw pointer (p->get());
    • for P(q) with an argument pointer q.
  • Some false negatives are not caused by the PR, because the same code with a function body behaves the same in base:
    • a std::string temporary or a by-value std::string parameter passed to a std::string_view parameter;
    • a call with explicit template arguments to a function that is only declared.

Robustness
These inputs did not crash or hang:

  • [[clang::lifetimebound]] alone;
  • void f([[clang::lifetimebound]]);
  • int x [[clang::lifetimebound]];
  • __attribute__((lifetimebound)) ;
  • () [[clang::lifetimebound]], which gives syntaxError;
  • noexcept() [[clang::lifetimebound]];
  • the attribute next to other attributes, and after noexcept(true).

Automated review of ec82405 by Claude. The pull request was built and tested locally.

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