/
checkautovariables.cpp
552 lines (476 loc) · 21.5 KB
/
checkautovariables.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
/*
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2016 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
//---------------------------------------------------------------------------
// Auto variables checks
//---------------------------------------------------------------------------
#include "checkautovariables.h"
#include "symboldatabase.h"
#include <string>
//---------------------------------------------------------------------------
// Register this check class into cppcheck by creating a static instance of it..
namespace {
static CheckAutoVariables instance;
}
static const CWE CWE398(398U); // Indicator of Poor Code Quality
static const CWE CWE562(562U); // Return of Stack Variable Address
static const CWE CWE590(590U); // Free of Memory not on the Heap
bool CheckAutoVariables::isPtrArg(const Token *tok)
{
const Variable *var = tok->variable();
return (var && var->isArgument() && var->isPointer());
}
bool CheckAutoVariables::isArrayArg(const Token *tok)
{
const Variable *var = tok->variable();
return (var && var->isArgument() && var->isArray());
}
bool CheckAutoVariables::isRefPtrArg(const Token *tok)
{
const Variable *var = tok->variable();
return (var && var->isArgument() && var->isReference() && var->isPointer());
}
bool CheckAutoVariables::isNonReferenceArg(const Token *tok)
{
const Variable *var = tok->variable();
return (var && var->isArgument() && !var->isReference() && (var->isPointer() || var->typeStartToken()->isStandardType() || var->type()));
}
bool CheckAutoVariables::isAutoVar(const Token *tok)
{
const Variable *var = tok->variable();
if (!var || !var->isLocal() || var->isStatic())
return false;
if (var->isReference()) {
// address of reference variable can be taken if the address
// of the variable it points at is not a auto-var
// TODO: check what the reference variable references.
return false;
}
if (Token::Match(tok, "%name% .|::")) {
do {
tok = tok->tokAt(2);
} while (Token::Match(tok, "%name% .|::"));
if (Token::Match(tok, "%name% ("))
return false;
}
return true;
}
bool CheckAutoVariables::isAutoVarArray(const Token *tok)
{
if (!tok)
return false;
// &x[..]
if (tok->str() == "&" && Token::simpleMatch(tok->astOperand1(), "[") && !tok->astOperand2())
return isAutoVarArray(tok->astOperand1()->astOperand1());
// x+y
if (tok->str() == "+")
return isAutoVarArray(tok->astOperand1()) || isAutoVarArray(tok->astOperand2());
// x-intexpr
if (tok->str() == "-")
return isAutoVarArray(tok->astOperand1()) &&
tok->astOperand2() &&
tok->astOperand2()->valueType() &&
tok->astOperand2()->valueType()->isIntegral();
const Variable *var = tok->variable();
if (!var)
return false;
// Variable
if (var->isLocal() && !var->isStatic() && var->isArray() && !var->isPointer())
return true;
// ValueFlow
if (var->isPointer() && !var->isArgument()) {
for (std::list<ValueFlow::Value>::const_iterator it = tok->values().begin(); it != tok->values().end(); ++it) {
const ValueFlow::Value &val = *it;
if (val.isTokValue() && isAutoVarArray(val.tokvalue))
return true;
}
}
return false;
}
// Verification that we really take the address of a local variable
static bool checkRvalueExpression(const Token * const vartok)
{
const Variable * const var = vartok->variable();
if (var == nullptr)
return false;
if (Token::Match(vartok->previous(), "& %name% [") && var->isPointer())
return false;
const Token * const next = vartok->next();
// &a.b[0]
if (Token::Match(vartok, "%name% . %var% [") && !var->isPointer()) {
const Variable *var2 = next->next()->variable();
return var2 && !var2->isPointer();
}
return ((next->str() != "." || (!var->isPointer() && (!var->isClass() || var->type()))) && next->strAt(2) != ".");
}
static bool variableIsUsedInScope(const Token* start, unsigned int varId, const Scope *scope)
{
if (!start) // Ticket #5024
return false;
for (const Token *tok = start; tok && tok != scope->classEnd; tok = tok->next()) {
if (tok->varId() == varId)
return true;
const Scope::ScopeType scopeType = tok->scope()->type;
if (scopeType == Scope::eFor || scopeType == Scope::eDo || scopeType == Scope::eWhile) // In case of loops, better checking would be necessary
return true;
if (Token::simpleMatch(tok, "asm ("))
return true;
}
return false;
}
void CheckAutoVariables::assignFunctionArg()
{
const bool printStyle = _settings->isEnabled(Settings::STYLE);
const bool printWarning = _settings->isEnabled(Settings::WARNING);
if (!printStyle && !printWarning)
return;
const SymbolDatabase *symbolDatabase = _tokenizer->getSymbolDatabase();
const std::size_t functions = symbolDatabase->functionScopes.size();
for (std::size_t i = 0; i < functions; ++i) {
const Scope * scope = symbolDatabase->functionScopes[i];
for (const Token *tok = scope->classStart; tok && tok != scope->classEnd; tok = tok->next()) {
// TODO: What happens if this is removed?
if (tok->astParent())
continue;
if (!Token::Match(tok, "=|++|--") || !Token::Match(tok->astOperand1(), "%var%"))
continue;
const Token* const vartok = tok->astOperand1();
if (isNonReferenceArg(vartok) &&
!Token::Match(vartok->next(), "= %varid% ;", vartok->varId()) &&
!variableIsUsedInScope(Token::findsimplematch(vartok->next(), ";"), vartok->varId(), scope) &&
!Token::findsimplematch(vartok, "goto", scope->classEnd)) {
if (vartok->variable()->isPointer() && printWarning)
errorUselessAssignmentPtrArg(vartok);
else if (printStyle)
errorUselessAssignmentArg(vartok);
}
}
}
}
void CheckAutoVariables::autoVariables()
{
const bool printInconclusive = _settings->inconclusive;
const SymbolDatabase *symbolDatabase = _tokenizer->getSymbolDatabase();
const std::size_t functions = symbolDatabase->functionScopes.size();
for (std::size_t i = 0; i < functions; ++i) {
const Scope * scope = symbolDatabase->functionScopes[i];
for (const Token *tok = scope->classStart; tok && tok != scope->classEnd; tok = tok->next()) {
// Critical assignment
if (Token::Match(tok, "[;{}] %var% = & %var%") && isRefPtrArg(tok->next()) && isAutoVar(tok->tokAt(4))) {
if (checkRvalueExpression(tok->tokAt(4)))
errorAutoVariableAssignment(tok->next(), false);
} else if (Token::Match(tok, "[;{}] * %var% = & %var%") && isPtrArg(tok->tokAt(2)) && isAutoVar(tok->tokAt(5))) {
if (checkRvalueExpression(tok->tokAt(5)))
errorAutoVariableAssignment(tok->next(), false);
} else if (Token::Match(tok, "[;{}] %var% . %var% = & %var%")) {
// TODO: check if the parameter is only changed temporarily (#2969)
if (printInconclusive && isPtrArg(tok->next())) {
const Token * const var2tok = tok->tokAt(6);
if (isAutoVar(var2tok) && checkRvalueExpression(var2tok))
errorAutoVariableAssignment(tok->next(), true);
}
tok = tok->tokAt(6);
} else if (Token::Match(tok, "[;{}] %var% . %var% = %var% ;")) {
// TODO: check if the parameter is only changed temporarily (#2969)
if (printInconclusive && isPtrArg(tok->next())) {
if (isAutoVarArray(tok->tokAt(5)))
errorAutoVariableAssignment(tok->next(), true);
}
tok = tok->tokAt(5);
} else if (Token::Match(tok, "[;{}] * %var% = %var% ;")) {
const Variable * var1 = tok->tokAt(2)->variable();
if (var1 && var1->isArgument() && Token::Match(var1->nameToken()->tokAt(-3), "%type% * *")) {
if (isAutoVarArray(tok->tokAt(4)))
errorAutoVariableAssignment(tok->next(), false);
}
tok = tok->tokAt(4);
} else if (Token::Match(tok, "[;{}] %var% [") && Token::Match(tok->linkAt(2), "] = & %var%") &&
(isPtrArg(tok->next()) || isArrayArg(tok->next())) && isAutoVar(tok->linkAt(2)->tokAt(3))) {
const Token* const varTok = tok->linkAt(2)->tokAt(3);
if (checkRvalueExpression(varTok))
errorAutoVariableAssignment(tok->next(), false);
}
// Critical return
else if (Token::Match(tok, "return & %var% ;")) {
const Token* varTok = tok->tokAt(2);
if (isAutoVar(varTok))
errorReturnAddressToAutoVariable(tok);
else if (varTok->varId()) {
const Variable * var1 = varTok->variable();
if (var1 && var1->isArgument() && var1->typeEndToken()->str() != "&")
errorReturnAddressOfFunctionParameter(tok, varTok->str());
}
}
// Invalid pointer deallocation
else if ((Token::Match(tok, "%name% ( %var% ) ;") && _settings->library.dealloc(tok)) ||
(_tokenizer->isCPP() && Token::Match(tok, "delete [| ]| (| %var% !!["))) {
tok = Token::findmatch(tok->next(), "%var%");
if (isAutoVarArray(tok))
errorInvalidDeallocation(tok);
} else if ((Token::Match(tok, "%name% ( & %var% ) ;") && _settings->library.dealloc(tok)) ||
(_tokenizer->isCPP() && Token::Match(tok, "delete [| ]| (| & %var% !!["))) {
tok = Token::findmatch(tok->next(), "%var%");
if (isAutoVar(tok))
errorInvalidDeallocation(tok);
}
}
}
}
//---------------------------------------------------------------------------
void CheckAutoVariables::returnPointerToLocalArray()
{
const SymbolDatabase *symbolDatabase = _tokenizer->getSymbolDatabase();
const std::size_t functions = symbolDatabase->functionScopes.size();
for (std::size_t i = 0; i < functions; ++i) {
const Scope * scope = symbolDatabase->functionScopes[i];
if (!scope->function)
continue;
const Token *tok = scope->function->tokenDef;
// have we reached a function that returns a pointer
if (tok->previous() && tok->previous()->str() == "*") {
for (const Token *tok2 = scope->classStart->next(); tok2 && tok2 != scope->classEnd; tok2 = tok2->next()) {
// Return pointer to local array variable..
if (tok2 ->str() == "return" && isAutoVarArray(tok2->astOperand1())) {
errorReturnPointerToLocalArray(tok2);
}
}
}
}
}
void CheckAutoVariables::errorReturnAddressToAutoVariable(const Token *tok)
{
reportError(tok, Severity::error, "returnAddressOfAutoVariable", "Address of an auto-variable returned.", CWE562, false);
}
void CheckAutoVariables::errorReturnPointerToLocalArray(const Token *tok)
{
reportError(tok, Severity::error, "returnLocalVariable", "Pointer to local array variable returned.", CWE562, false);
}
void CheckAutoVariables::errorAutoVariableAssignment(const Token *tok, bool inconclusive)
{
if (!inconclusive) {
reportError(tok, Severity::error, "autoVariables",
"Address of local auto-variable assigned to a function parameter.\n"
"Dangerous assignment - the function parameter is assigned the address of a local "
"auto-variable. Local auto-variables are reserved from the stack which "
"is freed when the function ends. So the pointer to a local variable "
"is invalid after the function ends.", CWE562, false);
} else {
reportError(tok, Severity::error, "autoVariables",
"Address of local auto-variable assigned to a function parameter.\n"
"Function parameter is assigned the address of a local auto-variable. "
"Local auto-variables are reserved from the stack which is freed when "
"the function ends. The address is invalid after the function ends and it "
"might 'leak' from the function through the parameter.",
CWE562,
true);
}
}
void CheckAutoVariables::errorReturnAddressOfFunctionParameter(const Token *tok, const std::string &varname)
{
reportError(tok, Severity::error, "returnAddressOfFunctionParameter",
"Address of function parameter '" + varname + "' returned.\n"
"Address of the function parameter '" + varname + "' becomes invalid after the function exits because "
"function parameters are stored on the stack which is freed when the function exits. Thus the returned "
"value is invalid.", CWE562, false);
}
void CheckAutoVariables::errorUselessAssignmentArg(const Token *tok)
{
reportError(tok,
Severity::style,
"uselessAssignmentArg",
"Assignment of function parameter has no effect outside the function.", CWE398, false);
}
void CheckAutoVariables::errorUselessAssignmentPtrArg(const Token *tok)
{
reportError(tok,
Severity::warning,
"uselessAssignmentPtrArg",
"Assignment of function parameter has no effect outside the function. Did you forget dereferencing it?", CWE398, false);
}
//---------------------------------------------------------------------------
// return temporary?
bool CheckAutoVariables::returnTemporary(const Token *tok)
{
bool func = false; // Might it be a function call?
bool retref = false; // is there such a function that returns a reference?
bool retvalue = false; // is there such a function that returns a value?
const Function *function = tok->function();
if (function) {
// Ticket #5478: Only functions or operator equal might return a temporary
if (function->type != Function::eOperatorEqual && function->type != Function::eFunction)
return false;
retref = function->tokenDef->strAt(-1) == "&";
if (!retref) {
const Token *start = function->retDef;
if (start->str() == "const")
start = start->next();
if (start->str() == "::")
start = start->next();
if (Token::simpleMatch(start, "std ::")) {
if (start->strAt(3) != "<" || !Token::simpleMatch(start->linkAt(3), "> ::"))
retvalue = true;
else
retref = true; // Assume that a reference is returned
} else {
if (start->type())
retvalue = true;
else
retref = true;
}
}
func = true;
}
if (!func && tok->type())
return true;
return bool(!retref && retvalue);
}
//---------------------------------------------------------------------------
static bool astHasAutoResult(const Token *tok)
{
if (tok->astOperand1() && !astHasAutoResult(tok->astOperand1()))
return false;
if (tok->astOperand2() && !astHasAutoResult(tok->astOperand2()))
return false;
if (tok->isOp()) {
if (tok->tokType() == Token::eIncDecOp)
return false;
if ((tok->str() == "<<" || tok->str() == ">>") && tok->astOperand1()) {
const Token* tok2 = tok->astOperand1();
while (tok2 && tok2->str() == "*" && !tok2->astOperand2())
tok2 = tok2->astOperand1();
return tok2 && tok2->variable() && !tok2->variable()->isClass() && !tok2->variable()->isStlType(); // Class or unknown type on LHS: Assume it is a stream
}
return true;
}
if (tok->isLiteral())
return true;
if (tok->isName()) {
// TODO: check function calls, struct members, arrays, etc also
if (!tok->variable())
return false;
if (tok->variable()->isStlType())
return true;
if (tok->variable()->isClass() || tok->variable()->isPointer() || tok->variable()->isReference()) // TODO: Properly handle pointers/references to classes in symbol database
return false;
return true;
}
return false;
}
/*!
* Skip over a lambda expression
* \return next token - or next token beyond lambda
* \todo handle explicit return type
*/
static const Token* skipLambda(const Token* first)
{
if (!first)
return nullptr;
if (first->str() != "[")
return first;
const Token* tok = first->link()->next();
if (!tok)
return nullptr;
if (tok->str() == "(") {
tok = tok->link()->next();
}
if (tok->str() == "constexpr")
tok = tok->next();
if (tok->str() == "mutable")
tok = tok->next();
if (tok->str() == "{") {
tok = tok->link()->next();
}
return tok;
}
void CheckAutoVariables::returnReference()
{
if (_tokenizer->isC())
return;
const SymbolDatabase *symbolDatabase = _tokenizer->getSymbolDatabase();
const std::size_t functions = symbolDatabase->functionScopes.size();
for (std::size_t i = 0; i < functions; ++i) {
const Scope * scope = symbolDatabase->functionScopes[i];
if (!scope->function)
continue;
const Token *tok = scope->function->tokenDef;
// have we reached a function that returns a reference?
if (tok->previous() && tok->previous()->str() == "&") {
for (const Token *tok2 = scope->classStart->next(); tok2 && tok2 != scope->classEnd; tok2 = tok2->next()) {
if (!tok2->scope()->isExecutable()) {
tok2 = tok2->scope()->classEnd;
continue;
}
// Skip over lambdas
tok2 = skipLambda(tok2);
if (!tok2)
break;
if (tok2->str() == "(")
tok2 = tok2->link();
if (tok2->str() != "return")
continue;
// return..
if (Token::Match(tok2, "return %var% ;")) {
// is the returned variable a local variable?
if (isAutoVar(tok2->next())) {
const Variable *var1 = tok2->next()->variable();
// If reference variable is used, check what it references
if (Token::Match(var1->nameToken(), "%var% [=(]")) {
const Token *tok3 = var1->nameToken()->tokAt(2);
if (!Token::Match(tok3, "%var% [);.]"))
continue;
// Only report error if variable that is referenced is
// a auto variable
if (!isAutoVar(tok3))
continue;
}
// report error..
errorReturnReference(tok2);
}
}
// return reference to temporary..
else if (Token::Match(tok2, "return %name% (") &&
Token::simpleMatch(tok2->linkAt(2), ") ;")) {
if (returnTemporary(tok2->next())) {
// report error..
errorReturnTempReference(tok2);
}
}
// Return reference to a literal or the result of a calculation
else if (tok2->astOperand1() && (tok2->astOperand1()->isCalculation() || tok2->next()->isLiteral()) && astHasAutoResult(tok2->astOperand1())) {
errorReturnTempReference(tok2);
}
}
}
}
}
void CheckAutoVariables::errorReturnReference(const Token *tok)
{
reportError(tok, Severity::error, "returnReference", "Reference to auto variable returned.", CWE562, false);
}
void CheckAutoVariables::errorReturnTempReference(const Token *tok)
{
reportError(tok, Severity::error, "returnTempReference", "Reference to temporary returned.", CWE562, false);
}
void CheckAutoVariables::errorInvalidDeallocation(const Token *tok)
{
reportError(tok,
Severity::error,
"autovarInvalidDeallocation",
"Deallocation of an auto-variable results in undefined behaviour.\n"
"The deallocation of an auto-variable results in undefined behaviour. You should only free memory "
"that has been allocated dynamically.", CWE590, false);
}