Repository navigation
Conversation
|
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
left a comment
There was a problem hiding this comment.
AI review
I found two new problems; nobody has raised either one yet.
- False positive on owning results (most important). The lifetimebound path never checks whether the result type can borrow at all. Owning types like
std::stringorstd::vector<int>get lifetime values anyway. Sostd::string u = upper(s); s += "b"; return u;gives bothreturnDanglingLifetimeandinvalidContaineronu, even thoughuis an independent copy. Code without the attribute does not do this, because it goes throughisLifetimeBorrowedon the returned expression. - Regression in constructors (false negative). If one constructor parameter has the attribute, the existing
hasBorrowingVariablesheuristic 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
cppcheckandtestrunnerfrom pr/, andcppcheckfrom base/. ./testrunner TestAutoVariables TestStl TestBufferOverrun TestSymbolDatabase TestTokenizer TestValueFlow: 1353 tests, 0 failed.- I pulled every code block out of
man/lifetimebound.mdand 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
invalidContainerReferenceresults changed. Each change matches what the PR description announces.
- Attribute spellings:
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
anow has the attribute.
Automated review of 2b2c0a1 by Claude. The pull request was built and tested locally.
| ls.type = getLifetimeBoundKind(boundArg.relation, isInteriorArgument(boundArg.tok, settings)); | ||
| return ls.byRef(tok, tokenlist, errorLogger, settings); | ||
| } | ||
| ls.byValKind = LifetimeBoundByValKind{boundArg.relation, astIsIterator(tok)}; |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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:
| ls.byVal(tok, tokenlist, errorLogger, settings); | ||
| }); | ||
| } else if (hasBorrowingVariables(constructor->nestedIn->varlist, args)) { | ||
| } else if (!lifetimeBound && hasBorrowingVariables(constructor->nestedIn->varlist, args)) { |
There was a problem hiding this comment.
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.
|
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/ 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
left a comment
There was a problem hiding this comment.
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
hasBorrowingVariableslifetimes. 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 wronglifetimebound. - 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 | |
| 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 testrunnerin pr/ built fine.make -j8 cppcheckin 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
lifetimeboundparameter and&ypassed 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 givesreturnDanglingLifetimeandinvalidContainer. 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.
- member functions with
- Views and iterators:
trim(s)andtrim2(s)tostd::string_viewfollowed bys += ...giveinvalidContainer;- an iterator passed through
nxt(it)followed bypush_backgivesinvalidContainer; P(&x)givesreturnDanglingLifetime.
- No false positives:
- for results of type
int; - for arguments passed through a raw pointer (
p->get()); - for
P(q)with an argument pointerq.
- for results of type
- Some false negatives are not caused by the PR, because the same code with a function body behaves the same in base:
- a
std::stringtemporary or a by-valuestd::stringparameter passed to astd::string_viewparameter; - a call with explicit template arguments to a function that is only declared.
- a
Robustness
These inputs did not crash or hang:
[[clang::lifetimebound]]alone;void f([[clang::lifetimebound]]);int x [[clang::lifetimebound]];__attribute__((lifetimebound)) ;() [[clang::lifetimebound]], which givessyntaxError;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.
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,
getLifetimeTokensnow 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 byinvalidContainerReferenceafter apush_back, andstd::string_view sv = s;and&*std::begin(v)are now reported byinvalidContainer. 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.