Skip to content

Commit 8fe6f71

Browse files
tropibyteclaude
andcommitted
Fix #12795 (FP knownConditionTrueFalse: object read through pointer may be changed by function call)
A member read through a local pointer ('p->i') was assumed unchanged across a function call, so 'o = p->i; modify(); if (p->i == o)' was reported as always true even when modify() can change the object. Dereferencing a pointer is now treated as non-local unless the pointer is known to point at a local object, or at memory from 'new' or a library allocation function (malloc, calloc, ...) whose address never escapes the function. 'new' of a type with a constructor or base class is treated conservatively, since the constructor could store 'this'. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1 parent 05ff791 commit 8fe6f71

3 files changed

Lines changed: 254 additions & 7 deletions

File tree

‎lib/vf_analyzers.cpp‎

Lines changed: 121 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1349,10 +1349,127 @@ struct ExpressionAnalyzer : SingleValueFlowAnalyzer {
13491349
}
13501350

13511351
static bool nonLocal(const Variable* var, bool deref) {
1352-
return !var || (!var->isLocal() && !var->isArgument()) || (deref && var->isArgument() && var->isPointer()) ||
1352+
return !var || (!var->isLocal() && !var->isArgument()) || (deref && var->isPointer()) ||
13531353
var->isStatic() || var->isReference() || var->isExtern();
13541354
}
13551355

1356+
// Is the expression that dereferences the pointer only read or written, so that the
1357+
// address of the object (or its members) does not escape?
1358+
static bool isLocalDerefUse(const Token* deref) {
1359+
const Token* parent = deref->astParent();
1360+
if (!parent)
1361+
return true;
1362+
if (parent->isUnaryOp("&"))
1363+
return false;
1364+
// member function call, 'this' might escape
1365+
if (Token::Match(deref, ". %name% ("))
1366+
return false;
1367+
// passed to function, might be passed by reference
1368+
if (Token::Match(parent, ",|(") && !parent->isCast() && !(parent->str() == "(" && Token::Match(parent->previous(), "if|while|switch")))
1369+
return false;
1370+
if (Token::Match(parent, "{|:|return|throw"))
1371+
return false;
1372+
// bound to reference
1373+
if (parent->str() == "=" && astIsRHS(deref) && parent->astOperand1() && parent->astOperand1()->variable() &&
1374+
parent->astOperand1()->variable()->isReference())
1375+
return false;
1376+
return true;
1377+
}
1378+
1379+
// Skip pointer casts, e.g. '(S*)malloc(n)' or 'static_cast<S*>(malloc(n))'
1380+
static const Token* skipPointerCasts(const Token* tok) {
1381+
while (Token::simpleMatch(tok, "(")) {
1382+
if (tok->isCast())
1383+
tok = tok->astOperand2() ? tok->astOperand2() : tok->astOperand1();
1384+
else if (Token::Match(tok->astOperand1(), "static_cast|reinterpret_cast"))
1385+
tok = tok->astOperand2();
1386+
else
1387+
break;
1388+
}
1389+
return tok;
1390+
}
1391+
1392+
// Is the memory allocated by a library allocation function, e.g. 'malloc(n)'?
1393+
static bool isLibraryMemoryAllocation(const Token* tok, const Settings& settings) {
1394+
tok = skipPointerCasts(tok);
1395+
// the function name is the token before '(', also for 'std::malloc(n)'
1396+
if (!Token::simpleMatch(tok, "(") || !tok->astOperand1() || !Token::Match(tok->previous(), "%name% ("))
1397+
return false;
1398+
const Library::AllocFunc* allocFunc = settings.library.getAllocFuncInfo(tok->previous());
1399+
return allocFunc && Library::ismemory(allocFunc);
1400+
}
1401+
1402+
// Does the local pointer point at an object allocated with 'new' or a library allocation function
1403+
// (e.g. malloc) that can't be accessed outside the function?
1404+
static bool pointsToLocalAllocation(const Variable* var, const Settings& settings) {
1405+
if (!var || !var->isLocal() || var->isStatic() || !var->isPointer() || var->isReference() || var->isArray())
1406+
return false;
1407+
const Token* assignTok = var->nameToken()->next();
1408+
if (Token::Match(assignTok, "; %varid% =", var->declarationId())) // declaration is split
1409+
assignTok = assignTok->tokAt(2);
1410+
if (!Token::simpleMatch(assignTok, "=") || !var->scope() || !var->scope()->bodyEnd)
1411+
return false;
1412+
const Token* allocTok = assignTok->astOperand2();
1413+
if (allocTok && allocTok->isKeyword() && allocTok->str() == "new") {
1414+
// The constructor might store the address of the object
1415+
const Token* typeTok = allocTok->next();
1416+
while (Token::Match(typeTok, "%name% ::"))
1417+
typeTok = typeTok->tokAt(2);
1418+
if (!Token::Match(typeTok, "%type%"))
1419+
return false; // placement new
1420+
if (!typeTok->isStandardType()) {
1421+
const Type* type = typeTok->type();
1422+
if (!type || !type->classScope || type->classScope->numConstructors > 0 || !type->derivedFrom.empty())
1423+
return false;
1424+
}
1425+
} else if (!isLibraryMemoryAllocation(allocTok, settings)) {
1426+
// No constructor is called for memory from an allocation function such as malloc
1427+
return false;
1428+
}
1429+
for (const Token* tok = assignTok; tok != var->scope()->bodyEnd; tok = tok->next()) {
1430+
if (tok->varId() != var->declarationId())
1431+
continue;
1432+
// The pointer is used in a lambda that might be called by another function
1433+
for (const Scope* scope = tok->scope(); scope && scope != var->scope(); scope = scope->nestedIn) {
1434+
if (scope->type == ScopeType::eLambda)
1435+
return false;
1436+
}
1437+
const Token* parent = tok->astParent();
1438+
if (!parent)
1439+
return false;
1440+
if (Token::Match(parent, "delete|!|%comp%|&&|%oror%"))
1441+
continue;
1442+
if (parent->str() == "(" && Token::Match(parent->previous(), "if|while ("))
1443+
continue;
1444+
// deallocated with a library function, e.g. 'free(p)'
1445+
if (parent->str() == "(" && parent->astOperand2() == tok && parent->astOperand1() && Token::Match(parent->previous(), "%name% (") &&
1446+
settings.library.getDeallocFuncInfo(parent->previous()))
1447+
continue;
1448+
if ((parent->isUnaryOp("*") || (parent->originalName() == "->" && astIsLHS(tok)) ||
1449+
(parent->str() == "[" && astIsLHS(tok))) && isLocalDerefUse(parent))
1450+
continue;
1451+
return false;
1452+
}
1453+
return true;
1454+
}
1455+
1456+
// Does the pointer point at a known local object?
1457+
static bool pointsToLocal(const Token* tok, const Settings& settings) {
1458+
if (pointsToLocalAllocation(tok->variable(), settings))
1459+
return true;
1460+
bool result = false;
1461+
for (const ValueFlow::Value& v : tok->values()) {
1462+
if (!v.isLifetimeValue())
1463+
continue;
1464+
if (!v.isLocalLifetimeValue() || v.isInconclusive() || v.lifetimeKind != ValueFlow::Value::LifetimeKind::Address)
1465+
return false;
1466+
if (!v.tokvalue || !v.tokvalue->variable() || nonLocal(v.tokvalue->variable(), false))
1467+
return false;
1468+
result = true;
1469+
}
1470+
return result;
1471+
}
1472+
13561473
void setupExprVarIds(const Token* start, int depth = 0) {
13571474
if (depth > settings().vfOptions.maxExprVarIdDepth) {
13581475
// TODO: add bailout message
@@ -1388,8 +1505,9 @@ struct ExpressionAnalyzer : SingleValueFlowAnalyzer {
13881505
return ChildrenToVisit::none;
13891506
const bool deref = tok->astParent() &&
13901507
(tok->astParent()->isUnaryOp("*") ||
1391-
(tok->astParent()->str() == "[" && tok == tok->astParent()->astOperand1()));
1392-
local &= !nonLocal(tok->variable(), deref);
1508+
(tok->astParent()->str() == "[" && tok == tok->astParent()->astOperand1()) ||
1509+
(tok->astParent()->originalName() == "->" && tok == tok->astParent()->astOperand1()));
1510+
local &= !nonLocal(tok->variable(), deref && !pointsToLocal(tok, settings()));
13931511
}
13941512
}
13951513
return ChildrenToVisit::op1_and_op2;

‎releasenotes.txt‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -26,4 +26,4 @@ Infrastructure & dependencies:
2626
and rule files work unchanged. On Windows the Visual Studio project now expects pcre2-8.lib and pcre2.h in externals.
2727

2828
Other:
29-
-
29+
- Fixed false positive knownConditionTrueFalse when a member is read through a pointer ('p->i') and a function call in between may change the object that the pointer points at (#12795).

‎test/testcondition.cpp‎

Lines changed: 132 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -5295,9 +5295,138 @@ class TestCondition : public TestFixture {
52955295
" t.modify();\n"
52965296
" if (p->i == o) {}\n"
52975297
"}\n");
5298-
TODO_ASSERT_EQUALS("",
5299-
"[test.cpp:11:14]: (style) Condition 'p->i==o' is always true [knownConditionTrueFalse]\n",
5300-
errout_str());
5298+
ASSERT_EQUALS("", errout_str());
5299+
5300+
// the object pointed at might be changed by the function call
5301+
check("struct S { int i; };\n"
5302+
"void modify();\n"
5303+
"void f(const S* p) {\n"
5304+
" const int o = p->i;\n"
5305+
" modify();\n"
5306+
" if (p->i == o) {}\n"
5307+
"}\n");
5308+
ASSERT_EQUALS("", errout_str());
5309+
5310+
check("struct S { int i; };\n"
5311+
"void modify();\n"
5312+
"const S* get();\n"
5313+
"void f() {\n"
5314+
" const S* p = get();\n"
5315+
" const int o = p->i;\n"
5316+
" modify();\n"
5317+
" if (p->i == o) {}\n"
5318+
"}\n");
5319+
ASSERT_EQUALS("", errout_str());
5320+
5321+
// the pointer points at a local object
5322+
check("struct S { int i; };\n"
5323+
"void modify();\n"
5324+
"void f() {\n"
5325+
" S s{};\n"
5326+
" const S* p = &s;\n"
5327+
" const int o = p->i;\n"
5328+
" modify();\n"
5329+
" if (p->i == o) {}\n"
5330+
"}\n");
5331+
ASSERT_EQUALS("[test.cpp:8:14]: (style) Condition 'p->i==o' is always true [knownConditionTrueFalse]\n", errout_str());
5332+
5333+
// the pointer points at an allocated object that can't be accessed by other code
5334+
check("struct S { int i; };\n"
5335+
"void modify();\n"
5336+
"void f() {\n"
5337+
" S* p = new S{};\n"
5338+
" const int o = p->i;\n"
5339+
" modify();\n"
5340+
" if (p->i == o) {}\n"
5341+
" delete p;\n"
5342+
"}\n");
5343+
ASSERT_EQUALS("[test.cpp:7:14]: (style) Condition 'p->i==o' is always true [knownConditionTrueFalse]\n", errout_str());
5344+
5345+
// the allocated object escapes
5346+
check("struct S { int i; };\n"
5347+
"void modify();\n"
5348+
"void g(S*);\n"
5349+
"void f() {\n"
5350+
" S* p = new S{};\n"
5351+
" g(p);\n"
5352+
" const int o = p->i;\n"
5353+
" modify();\n"
5354+
" if (p->i == o) {}\n"
5355+
"}\n");
5356+
ASSERT_EQUALS("", errout_str());
5357+
5358+
check("struct S { int i; };\n"
5359+
"void modify();\n"
5360+
"void g(int&);\n"
5361+
"void f() {\n"
5362+
" S* p = new S{};\n"
5363+
" g(p->i);\n"
5364+
" const int o = p->i;\n"
5365+
" modify();\n"
5366+
" if (p->i == o) {}\n"
5367+
"}\n");
5368+
ASSERT_EQUALS("", errout_str());
5369+
5370+
check("struct S { int i; };\n"
5371+
"void modify();\n"
5372+
"S* f() {\n"
5373+
" S* p = new S{};\n"
5374+
" const int o = p->i;\n"
5375+
" modify();\n"
5376+
" if (p->i == o) {}\n"
5377+
" return p;\n"
5378+
"}\n");
5379+
ASSERT_EQUALS("", errout_str());
5380+
5381+
// the constructor might store the address of the object
5382+
check("struct S { S(); int i; };\n"
5383+
"void modify();\n"
5384+
"void f() {\n"
5385+
" S* p = new S;\n"
5386+
" const int o = p->i;\n"
5387+
" modify();\n"
5388+
" if (p->i == o) {}\n"
5389+
" delete p;\n"
5390+
"}\n");
5391+
ASSERT_EQUALS("", errout_str());
5392+
5393+
// memory from a library allocation function that can't be accessed outside the function
5394+
check("struct S { int i; };\n"
5395+
"void modify(void);\n"
5396+
"void f(void) {\n"
5397+
" struct S* p = calloc(1, sizeof(struct S));\n"
5398+
" if (!p) return;\n"
5399+
" const int o = p->i;\n"
5400+
" modify();\n"
5401+
" if (p->i == o) {}\n"
5402+
" free(p);\n"
5403+
"}\n", dinit(CheckOptions, $.cpp = false));
5404+
ASSERT_EQUALS("[test.c:8:14]: (style) Condition 'p->i==o' is always true [knownConditionTrueFalse]\n", errout_str());
5405+
5406+
check("struct S { int i; };\n"
5407+
"void modify();\n"
5408+
"void f() {\n"
5409+
" S* p = static_cast<S*>(std::malloc(sizeof(S)));\n"
5410+
" const int o = p->i;\n"
5411+
" modify();\n"
5412+
" if (p->i == o) {}\n"
5413+
" std::free(p);\n"
5414+
"}\n");
5415+
ASSERT_EQUALS("[test.cpp:7:14]: (style) Condition 'p->i==o' is always true [knownConditionTrueFalse]\n", errout_str());
5416+
5417+
// the allocated memory escapes
5418+
check("struct S { int i; };\n"
5419+
"void modify(void);\n"
5420+
"void g(struct S*);\n"
5421+
"void f(void) {\n"
5422+
" struct S* p = calloc(1, sizeof(struct S));\n"
5423+
" g(p);\n"
5424+
" const int o = p->i;\n"
5425+
" modify();\n"
5426+
" if (p->i == o) {}\n"
5427+
" free(p);\n"
5428+
"}\n", dinit(CheckOptions, $.cpp = false));
5429+
ASSERT_EQUALS("", errout_str());
53015430

53025431
check("void f(int x) {\n" // #12320
53035432
" int a = 0, b = 0, c = 0;\n"

0 commit comments

Comments
 (0)