forked from danmar/cppcheck
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcheckcondition.cpp
1759 lines (1551 loc) · 76.2 KB
/
checkcondition.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
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2021 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/>.
*/
//---------------------------------------------------------------------------
// Check for condition mismatches
//---------------------------------------------------------------------------
#include "checkcondition.h"
#include "astutils.h"
#include "settings.h"
#include "symboldatabase.h"
#include "token.h"
#include "tokenize.h"
#include "valueflow.h"
#include "checkother.h" // comparisonNonZeroExpressionLessThanZero and testIfNonZeroExpressionIsPositive
#include <algorithm>
#include <limits>
#include <list>
#include <set>
#include <utility>
// CWE ids used
static const struct CWE uncheckedErrorConditionCWE(391U);
static const struct CWE CWE398(398U); // Indicator of Poor Code Quality
static const struct CWE CWE570(570U); // Expression is Always False
static const struct CWE CWE571(571U); // Expression is Always True
//---------------------------------------------------------------------------
// Register this check class (by creating a static instance of it)
namespace {
CheckCondition instance;
}
bool CheckCondition::diag(const Token* tok, bool insert)
{
if (!tok)
return false;
const Token* parent = tok->astParent();
bool hasParent = false;
while (Token::Match(parent, "&&|%oror%")) {
if (mCondDiags.count(parent) != 0) {
hasParent = true;
break;
}
parent = parent->astParent();
}
if (mCondDiags.count(tok) == 0 && !hasParent) {
if (insert)
mCondDiags.insert(tok);
return false;
}
return true;
}
bool CheckCondition::isAliased(const std::set<int> &vars) const
{
for (const Token *tok = mTokenizer->tokens(); tok; tok = tok->next()) {
if (Token::Match(tok, "= & %var% ;") && vars.find(tok->tokAt(2)->varId()) != vars.end())
return true;
}
return false;
}
void CheckCondition::assignIf()
{
if (!mSettings->severity.isEnabled(Severity::style))
return;
for (const Token *tok = mTokenizer->tokens(); tok; tok = tok->next()) {
if (tok->str() != "=")
continue;
if (Token::Match(tok->tokAt(-2), "[;{}] %var% =")) {
const Variable *var = tok->previous()->variable();
if (var == nullptr)
continue;
char bitop = '\0';
MathLib::bigint num = 0;
if (Token::Match(tok->next(), "%num% [&|]")) {
bitop = tok->strAt(2).at(0);
num = MathLib::toLongNumber(tok->next()->str());
} else {
const Token *endToken = Token::findsimplematch(tok, ";");
// Casting address
if (endToken && Token::Match(endToken->tokAt(-4), "* ) & %any% ;"))
endToken = nullptr;
if (endToken && Token::Match(endToken->tokAt(-2), "[&|] %num% ;")) {
bitop = endToken->strAt(-2).at(0);
num = MathLib::toLongNumber(endToken->previous()->str());
}
}
if (bitop == '\0')
continue;
if (num < 0 && bitop == '|')
continue;
assignIfParseScope(tok, tok->tokAt(4), var->declarationId(), var->isLocal(), bitop, num);
}
}
}
static bool isParameterChanged(const Token *partok)
{
bool addressOf = Token::Match(partok, "[(,] &");
int argumentNumber = 0;
const Token *ftok;
for (ftok = partok; ftok && ftok->str() != "("; ftok = ftok->previous()) {
if (ftok->str() == ")")
ftok = ftok->link();
else if (argumentNumber == 0U && ftok->str() == "&")
addressOf = true;
else if (ftok->str() == ",")
argumentNumber++;
}
ftok = ftok ? ftok->previous() : nullptr;
if (!(ftok && ftok->function()))
return true;
const Variable *par = ftok->function()->getArgumentVar(argumentNumber);
if (!par)
return true;
if (par->isConst())
return false;
if (addressOf || par->isReference() || par->isPointer())
return true;
return false;
}
/** parse scopes recursively */
bool CheckCondition::assignIfParseScope(const Token * const assignTok,
const Token * const startTok,
const nonneg int varid,
const bool islocal,
const char bitop,
const MathLib::bigint num)
{
bool ret = false;
for (const Token *tok2 = startTok; tok2; tok2 = tok2->next()) {
if ((bitop == '&') && Token::Match(tok2->tokAt(2), "%varid% %cop% %num% ;", varid) && tok2->strAt(3) == std::string(1U, bitop)) {
const MathLib::bigint num2 = MathLib::toLongNumber(tok2->strAt(4));
if (0 == (num & num2))
mismatchingBitAndError(assignTok, num, tok2, num2);
}
if (Token::Match(tok2, "%varid% =", varid)) {
return true;
}
if (bitop == '&' && Token::Match(tok2, "%varid% &= %num% ;", varid)) {
const MathLib::bigint num2 = MathLib::toLongNumber(tok2->strAt(2));
if (0 == (num & num2))
mismatchingBitAndError(assignTok, num, tok2, num2);
}
if (Token::Match(tok2, "++|-- %varid%", varid) || Token::Match(tok2, "%varid% ++|--", varid))
return true;
if (Token::Match(tok2, "[(,] &| %varid% [,)]", varid) && isParameterChanged(tok2))
return true;
if (tok2->str() == "}")
return false;
if (Token::Match(tok2, "break|continue|return"))
ret = true;
if (ret && tok2->str() == ";")
return false;
if (!islocal && Token::Match(tok2, "%name% (") && !Token::simpleMatch(tok2->next()->link(), ") {"))
return true;
if (Token::Match(tok2, "if|while (")) {
if (!islocal && tok2->str() == "while")
continue;
if (tok2->str() == "while") {
// is variable changed in loop?
const Token *bodyStart = tok2->linkAt(1)->next();
const Token *bodyEnd = bodyStart ? bodyStart->link() : nullptr;
if (!bodyEnd || bodyEnd->str() != "}" || isVariableChanged(bodyStart, bodyEnd, varid, !islocal, mSettings, mTokenizer->isCPP()))
continue;
}
// parse condition
const Token * const end = tok2->next()->link();
for (; tok2 != end; tok2 = tok2->next()) {
if (Token::Match(tok2, "[(,] &| %varid% [,)]", varid)) {
return true;
}
if (Token::Match(tok2,"&&|%oror%|( %varid% ==|!= %num% &&|%oror%|)", varid)) {
const Token *vartok = tok2->next();
const MathLib::bigint num2 = MathLib::toLongNumber(vartok->strAt(2));
if ((num & num2) != ((bitop=='&') ? num2 : num)) {
const std::string& op(vartok->strAt(1));
const bool alwaysTrue = op == "!=";
const std::string condition(vartok->str() + op + vartok->strAt(2));
assignIfError(assignTok, tok2, condition, alwaysTrue);
}
}
if (Token::Match(tok2, "%varid% %op%", varid) && tok2->next()->isAssignmentOp()) {
return true;
}
}
const bool ret1 = assignIfParseScope(assignTok, end->tokAt(2), varid, islocal, bitop, num);
bool ret2 = false;
if (Token::simpleMatch(end->next()->link(), "} else {"))
ret2 = assignIfParseScope(assignTok, end->next()->link()->tokAt(3), varid, islocal, bitop, num);
if (ret1 || ret2)
return true;
}
}
return false;
}
void CheckCondition::assignIfError(const Token *tok1, const Token *tok2, const std::string &condition, bool result)
{
if (tok2 && diag(tok2->tokAt(2)))
return;
std::list<const Token *> locations = { tok1, tok2 };
reportError(locations,
Severity::style,
"assignIfError",
"Mismatching assignment and comparison, comparison '" + condition + "' is always " + std::string(result ? "true" : "false") + ".", CWE398, Certainty::normal);
}
void CheckCondition::mismatchingBitAndError(const Token *tok1, const MathLib::bigint num1, const Token *tok2, const MathLib::bigint num2)
{
std::list<const Token *> locations = { tok1, tok2 };
std::ostringstream msg;
msg << "Mismatching bitmasks. Result is always 0 ("
<< "X = Y & 0x" << std::hex << num1 << "; Z = X & 0x" << std::hex << num2 << "; => Z=0).";
reportError(locations,
Severity::style,
"mismatchingBitAnd",
msg.str(), CWE398, Certainty::normal);
}
static void getnumchildren(const Token *tok, std::list<MathLib::bigint> &numchildren)
{
if (tok->astOperand1() && tok->astOperand1()->isNumber())
numchildren.push_back(MathLib::toLongNumber(tok->astOperand1()->str()));
else if (tok->astOperand1() && tok->str() == tok->astOperand1()->str())
getnumchildren(tok->astOperand1(), numchildren);
if (tok->astOperand2() && tok->astOperand2()->isNumber())
numchildren.push_back(MathLib::toLongNumber(tok->astOperand2()->str()));
else if (tok->astOperand2() && tok->str() == tok->astOperand2()->str())
getnumchildren(tok->astOperand2(), numchildren);
}
/* Return whether tok is in the body for a function returning a boolean. */
static bool inBooleanFunction(const Token *tok)
{
const Scope *scope = tok ? tok->scope() : nullptr;
while (scope && scope->isLocal())
scope = scope->nestedIn;
if (scope && scope->type == Scope::eFunction) {
const Function *func = scope->function;
if (func) {
const Token *ret = func->retDef;
while (Token::Match(ret, "static|const"))
ret = ret->next();
return Token::Match(ret, "bool|_Bool");
}
}
return false;
}
void CheckCondition::checkBadBitmaskCheck()
{
if (!mSettings->severity.isEnabled(Severity::warning))
return;
for (const Token *tok = mTokenizer->tokens(); tok; tok = tok->next()) {
if (tok->str() == "|" && tok->astOperand1() && tok->astOperand2() && tok->astParent()) {
const Token* parent = tok->astParent();
const bool isBoolean = Token::Match(parent, "&&|%oror%") ||
(parent->str() == "?" && parent->astOperand1() == tok) ||
(parent->str() == "=" && parent->astOperand2() == tok && parent->astOperand1() && parent->astOperand1()->variable() && Token::Match(parent->astOperand1()->variable()->typeStartToken(), "bool|_Bool")) ||
(parent->str() == "(" && Token::Match(parent->astOperand1(), "if|while")) ||
(parent->str() == "return" && parent->astOperand1() == tok && inBooleanFunction(tok));
const bool isTrue = (tok->astOperand1()->hasKnownIntValue() && tok->astOperand1()->values().front().intvalue != 0) ||
(tok->astOperand2()->hasKnownIntValue() && tok->astOperand2()->values().front().intvalue != 0);
if (isBoolean && isTrue)
badBitmaskCheckError(tok);
}
}
}
void CheckCondition::badBitmaskCheckError(const Token *tok)
{
reportError(tok, Severity::warning, "badBitmaskCheck", "Result of operator '|' is always true if one operand is non-zero. Did you intend to use '&'?", CWE571, Certainty::normal);
}
void CheckCondition::comparison()
{
if (!mSettings->severity.isEnabled(Severity::style))
return;
for (const Token *tok = mTokenizer->tokens(); tok; tok = tok->next()) {
if (!tok->isComparisonOp())
continue;
const Token *expr1 = tok->astOperand1();
const Token *expr2 = tok->astOperand2();
if (!expr1 || !expr2)
continue;
if (expr1->isNumber())
std::swap(expr1,expr2);
if (!expr2->isNumber())
continue;
const MathLib::bigint num2 = MathLib::toLongNumber(expr2->str());
if (num2 < 0)
continue;
if (!Token::Match(expr1,"[&|]"))
continue;
std::list<MathLib::bigint> numbers;
getnumchildren(expr1, numbers);
for (const MathLib::bigint num1 : numbers) {
if (num1 < 0)
continue;
if (Token::Match(tok, "==|!=")) {
if ((expr1->str() == "&" && (num1 & num2) != num2) ||
(expr1->str() == "|" && (num1 | num2) != num2)) {
const std::string& op(tok->str());
comparisonError(expr1, expr1->str(), num1, op, num2, op=="==" ? false : true);
}
} else if (expr1->str() == "&") {
const bool or_equal = Token::Match(tok, ">=|<=");
const std::string& op(tok->str());
if ((Token::Match(tok, ">=|<")) && (num1 < num2)) {
comparisonError(expr1, expr1->str(), num1, op, num2, or_equal ? false : true);
} else if ((Token::Match(tok, "<=|>")) && (num1 <= num2)) {
comparisonError(expr1, expr1->str(), num1, op, num2, or_equal ? true : false);
}
} else if (expr1->str() == "|") {
if ((expr1->astOperand1()->valueType()) &&
(expr1->astOperand1()->valueType()->sign == ValueType::Sign::UNSIGNED)) {
const bool or_equal = Token::Match(tok, ">=|<=");
const std::string& op(tok->str());
if ((Token::Match(tok, ">=|<")) && (num1 >= num2)) {
//"(a | 0x07) >= 7U" is always true for unsigned a
//"(a | 0x07) < 7U" is always false for unsigned a
comparisonError(expr1, expr1->str(), num1, op, num2, or_equal ? true : false);
} else if ((Token::Match(tok, "<=|>")) && (num1 > num2)) {
//"(a | 0x08) <= 7U" is always false for unsigned a
//"(a | 0x07) > 6U" is always true for unsigned a
comparisonError(expr1, expr1->str(), num1, op, num2, or_equal ? false : true);
}
}
}
}
}
}
void CheckCondition::comparisonError(const Token *tok, const std::string &bitop, MathLib::bigint value1, const std::string &op, MathLib::bigint value2, bool result)
{
std::ostringstream expression;
expression << std::hex << "(X " << bitop << " 0x" << value1 << ") " << op << " 0x" << value2;
const std::string errmsg("Expression '" + expression.str() + "' is always " + (result?"true":"false") + ".\n"
"The expression '" + expression.str() + "' is always " + (result?"true":"false") +
". Check carefully constants and operators used, these errors might be hard to "
"spot sometimes. In case of complex expression it might help to split it to "
"separate expressions.");
reportError(tok, Severity::style, "comparisonError", errmsg, CWE398, Certainty::normal);
}
bool CheckCondition::isOverlappingCond(const Token * const cond1, const Token * const cond2, bool pure) const
{
if (!cond1 || !cond2)
return false;
// same expressions
if (isSameExpression(mTokenizer->isCPP(), true, cond1, cond2, mSettings->library, pure, false))
return true;
// bitwise overlap for example 'x&7' and 'x==1'
if (cond1->str() == "&" && cond1->astOperand1() && cond2->astOperand2()) {
const Token *expr1 = cond1->astOperand1();
const Token *num1 = cond1->astOperand2();
if (!num1) // unary operator&
return false;
if (!num1->isNumber())
std::swap(expr1,num1);
if (!num1->isNumber() || MathLib::isNegative(num1->str()))
return false;
if (!Token::Match(cond2, "&|==") || !cond2->astOperand1() || !cond2->astOperand2())
return false;
const Token *expr2 = cond2->astOperand1();
const Token *num2 = cond2->astOperand2();
if (!num2->isNumber())
std::swap(expr2,num2);
if (!num2->isNumber() || MathLib::isNegative(num2->str()))
return false;
if (!isSameExpression(mTokenizer->isCPP(), true, expr1, expr2, mSettings->library, pure, false))
return false;
const MathLib::bigint value1 = MathLib::toLongNumber(num1->str());
const MathLib::bigint value2 = MathLib::toLongNumber(num2->str());
if (cond2->str() == "&")
return ((value1 & value2) == value2);
return ((value1 & value2) > 0);
}
return false;
}
void CheckCondition::duplicateCondition()
{
if (!mSettings->severity.isEnabled(Severity::style))
return;
const SymbolDatabase *const symbolDatabase = mTokenizer->getSymbolDatabase();
for (const Scope &scope : symbolDatabase->scopeList) {
if (scope.type != Scope::eIf)
continue;
const Token *cond1 = scope.classDef->next()->astOperand2();
if (!cond1)
continue;
if (cond1->hasKnownIntValue())
continue;
const Token *tok2 = scope.classDef->next();
if (!tok2)
continue;
tok2 = tok2->link();
if (!Token::simpleMatch(tok2, ") {"))
continue;
tok2 = tok2->linkAt(1);
if (!Token::simpleMatch(tok2, "} if ("))
continue;
const Token *cond2 = tok2->tokAt(2)->astOperand2();
if (!cond2)
continue;
ErrorPath errorPath;
if (!isExpressionChanged(cond1, scope.classDef->next(), cond2, mSettings, mTokenizer->isCPP()) &&
isSameExpression(mTokenizer->isCPP(), true, cond1, cond2, mSettings->library, true, true, &errorPath))
duplicateConditionError(cond1, cond2, errorPath);
}
}
void CheckCondition::duplicateConditionError(const Token *tok1, const Token *tok2, ErrorPath errorPath)
{
if (diag(tok1) & diag(tok2))
return;
errorPath.emplace_back(tok1, "First condition");
errorPath.emplace_back(tok2, "Second condition");
std::string msg = "The if condition is the same as the previous if condition";
reportError(errorPath, Severity::style, "duplicateCondition", msg, CWE398, Certainty::normal);
}
void CheckCondition::multiCondition()
{
if (!mSettings->severity.isEnabled(Severity::style))
return;
const SymbolDatabase* const symbolDatabase = mTokenizer->getSymbolDatabase();
for (const Scope &scope : symbolDatabase->scopeList) {
if (scope.type != Scope::eIf)
continue;
const Token * const cond1 = scope.classDef->next()->astOperand2();
if (!cond1)
continue;
const Token * tok2 = scope.classDef->next();
// Check each 'else if'
for (;;) {
tok2 = tok2->link();
if (!Token::simpleMatch(tok2, ") {"))
break;
tok2 = tok2->linkAt(1);
if (!Token::simpleMatch(tok2, "} else { if ("))
break;
tok2 = tok2->tokAt(4);
if (tok2->astOperand2()) {
ErrorPath errorPath;
if (isOverlappingCond(cond1, tok2->astOperand2(), true))
overlappingElseIfConditionError(tok2->astOperand2(), cond1->linenr());
else if (isOppositeCond(true, mTokenizer->isCPP(), cond1, tok2->astOperand2(), mSettings->library, true, true, &errorPath))
oppositeElseIfConditionError(cond1, tok2->astOperand2(), errorPath);
}
}
}
}
void CheckCondition::overlappingElseIfConditionError(const Token *tok, nonneg int line1)
{
if (diag(tok))
return;
std::ostringstream errmsg;
errmsg << "Expression is always false because 'else if' condition matches previous condition at line "
<< line1 << ".";
reportError(tok, Severity::style, "multiCondition", errmsg.str(), CWE398, Certainty::normal);
}
void CheckCondition::oppositeElseIfConditionError(const Token *ifCond, const Token *elseIfCond, ErrorPath errorPath)
{
if (diag(ifCond) & diag(elseIfCond))
return;
std::ostringstream errmsg;
errmsg << "Expression is always true because 'else if' condition is opposite to previous condition at line "
<< ifCond->linenr() << ".";
errorPath.emplace_back(ifCond, "first condition");
errorPath.emplace_back(elseIfCond, "else if condition is opposite to first condition");
reportError(errorPath, Severity::style, "multiCondition", errmsg.str(), CWE398, Certainty::normal);
}
//---------------------------------------------------------------------------
// - Opposite inner conditions => always false
// - (TODO) Same/Overlapping inner condition => always true
// - same condition after early exit => always false
//---------------------------------------------------------------------------
static bool isNonConstFunctionCall(const Token *ftok, const Library &library)
{
if (library.isFunctionConst(ftok))
return false;
const Token *obj = ftok->next()->astOperand1();
while (obj && obj->str() == ".")
obj = obj->astOperand1();
if (!obj)
return true;
else if (obj->variable() && obj->variable()->isConst())
return false;
else if (ftok->function() && ftok->function()->isConst())
return false;
return true;
}
void CheckCondition::multiCondition2()
{
if (!mSettings->severity.isEnabled(Severity::warning))
return;
const SymbolDatabase *symbolDatabase = mTokenizer->getSymbolDatabase();
for (const Scope &scope : symbolDatabase->scopeList) {
const Token *condTok = nullptr;
if (scope.type == Scope::eIf || scope.type == Scope::eWhile)
condTok = scope.classDef->next()->astOperand2();
else if (scope.type == Scope::eFor) {
condTok = scope.classDef->next()->astOperand2();
if (!condTok || condTok->str() != ";")
continue;
condTok = condTok->astOperand2();
if (!condTok || condTok->str() != ";")
continue;
condTok = condTok->astOperand1();
}
if (!condTok)
continue;
const Token * const cond1 = condTok;
if (!Token::simpleMatch(scope.classDef->linkAt(1), ") {"))
continue;
bool functionCall = false;
bool nonConstFunctionCall = false;
bool nonlocal = false; // nonlocal variable used in condition
std::set<int> vars; // variables used in condition
visitAstNodes(condTok,
[&](const Token *cond) {
if (Token::Match(cond, "%name% (")) {
functionCall = true;
nonConstFunctionCall = isNonConstFunctionCall(cond, mSettings->library);
if (nonConstFunctionCall)
return ChildrenToVisit::done;
}
if (cond->varId()) {
vars.insert(cond->varId());
const Variable *var = cond->variable();
if (!nonlocal && var) {
if (!(var->isLocal() || var->isArgument()))
nonlocal = true;
else if ((var->isPointer() || var->isReference()) && !Token::Match(cond->astParent(), "%oror%|&&|!"))
// TODO: if var is pointer check what it points at
nonlocal = true;
}
} else if (!nonlocal && cond->isName()) {
// varid is 0. this is possibly a nonlocal variable..
nonlocal = Token::Match(cond->astParent(), "%cop%|(|[") || Token::Match(cond, "%name% .") || (mTokenizer->isCPP() && cond->str() == "this");
} else {
return ChildrenToVisit::op1_and_op2;
}
return ChildrenToVisit::none;
});
if (nonConstFunctionCall)
continue;
std::vector<const Variable*> varsInCond;
visitAstNodes(condTok,
[&varsInCond](const Token *cond) {
if (cond->variable()) {
const Variable *var = cond->variable();
if (std::find(varsInCond.begin(), varsInCond.end(), var) == varsInCond.end())
varsInCond.push_back(var);
}
return ChildrenToVisit::op1_and_op2;
});
// parse until second condition is reached..
enum MULTICONDITIONTYPE { INNER, AFTER };
const Token *tok;
// Parse inner condition first and then early return condition
std::vector<MULTICONDITIONTYPE> types = {MULTICONDITIONTYPE::INNER};
if (Token::Match(scope.bodyStart, "{ return|throw|continue|break"))
types.push_back(MULTICONDITIONTYPE::AFTER);
for (MULTICONDITIONTYPE type:types) {
if (type == MULTICONDITIONTYPE::AFTER) {
tok = scope.bodyEnd->next();
} else {
tok = scope.bodyStart;
}
const Token * const endToken = tok->scope()->bodyEnd;
for (; tok && tok != endToken; tok = tok->next()) {
if (Token::Match(tok, "if|return")) {
const Token * condStartToken = tok->str() == "if" ? tok->next() : tok;
const Token * condEndToken = tok->str() == "if" ? condStartToken->link() : Token::findsimplematch(condStartToken, ";");
// Does condition modify tracked variables?
if (const Token *op = Token::findmatch(tok, "++|--", condEndToken)) {
bool bailout = false;
while (op) {
if (vars.find(op->astOperand1()->varId()) != vars.end()) {
bailout = true;
break;
}
if (nonlocal && op->astOperand1()->varId() == 0) {
bailout = true;
break;
}
op = Token::findmatch(op->next(), "++|--", condEndToken);
}
if (bailout)
break;
}
// Condition..
const Token *cond2 = tok->str() == "if" ? condStartToken->astOperand2() : condStartToken->astOperand1();
const bool isReturnVar = (tok->str() == "return" && !Token::Match(cond2, "%cop%"));
ErrorPath errorPath;
if (type == MULTICONDITIONTYPE::INNER) {
visitAstNodes(cond1, [&](const Token* firstCondition) {
if (!firstCondition)
return ChildrenToVisit::none;
if (firstCondition->str() == "&&") {
if (!isOppositeCond(false, mTokenizer->isCPP(), firstCondition, cond2, mSettings->library, true, true))
return ChildrenToVisit::op1_and_op2;
}
if (!firstCondition->hasKnownIntValue()) {
if (!isReturnVar && isOppositeCond(false, mTokenizer->isCPP(), firstCondition, cond2, mSettings->library, true, true, &errorPath)) {
if (!isAliased(vars))
oppositeInnerConditionError(firstCondition, cond2, errorPath);
} else if (!isReturnVar && isSameExpression(mTokenizer->isCPP(), true, firstCondition, cond2, mSettings->library, true, true, &errorPath)) {
identicalInnerConditionError(firstCondition, cond2, errorPath);
}
}
return ChildrenToVisit::none;
});
} else {
visitAstNodes(cond2, [&](const Token *secondCondition) {
if (secondCondition->str() == "||" || secondCondition->str() == "&&")
return ChildrenToVisit::op1_and_op2;
if ((!cond1->hasKnownIntValue() || !secondCondition->hasKnownIntValue()) &&
isSameExpression(mTokenizer->isCPP(), true, cond1, secondCondition, mSettings->library, true, true, &errorPath)) {
if (!isAliased(vars) && !mTokenizer->hasIfdef(cond1, secondCondition)) {
identicalConditionAfterEarlyExitError(cond1, secondCondition, errorPath);
return ChildrenToVisit::done;
}
}
return ChildrenToVisit::none;
});
}
}
if (Token::Match(tok, "%name% (") &&
isVariablesChanged(tok, tok->linkAt(1), 0, varsInCond, mSettings, mTokenizer->isCPP())) {
break;
}
if (Token::Match(tok, "%type% (") && nonlocal && isNonConstFunctionCall(tok, mSettings->library)) // non const function call -> bailout if there are nonlocal variables
break;
if (Token::Match(tok, "case|break|continue|return|throw") && tok->scope() == endToken->scope())
break;
if (Token::Match(tok, "[;{}] %name% :"))
break;
// bailout if loop is seen.
// TODO: handle loops better.
if (Token::Match(tok, "for|while|do")) {
const Token *tok1 = tok->next();
const Token *tok2;
if (Token::simpleMatch(tok, "do {")) {
if (!Token::simpleMatch(tok->linkAt(1), "} while ("))
break;
tok2 = tok->linkAt(1)->linkAt(2);
} else if (Token::Match(tok, "if|while (")) {
tok2 = tok->linkAt(1);
if (Token::simpleMatch(tok2, ") {"))
tok2 = tok2->linkAt(1);
if (!tok2)
break;
} else {
// Incomplete code
break;
}
bool changed = false;
for (int varid : vars) {
if (isVariableChanged(tok1, tok2, varid, nonlocal, mSettings, mTokenizer->isCPP())) {
changed = true;
break;
}
}
if (changed)
break;
}
if ((tok->varId() && vars.find(tok->varId()) != vars.end()) ||
(!tok->varId() && nonlocal) ||
(functionCall && tok->variable() && !tok->variable()->isLocal())) {
if (Token::Match(tok, "%name% %assign%|++|--"))
break;
if (Token::Match(tok->astParent(), "*|.|[")) {
const Token *parent = tok;
while (Token::Match(parent->astParent(), ".|[") || (parent->astParent() && parent->astParent()->isUnaryOp("*")))
parent = parent->astParent();
if (Token::Match(parent->astParent(), "%assign%|++|--"))
break;
}
if (mTokenizer->isCPP() && Token::Match(tok, "%name% <<") && (!tok->valueType() || !tok->valueType()->isIntegral()))
break;
if (isLikelyStreamRead(mTokenizer->isCPP(), tok->next()) || isLikelyStreamRead(mTokenizer->isCPP(), tok->previous()))
break;
if (Token::Match(tok, "%name% [")) {
const Token *tok2 = tok->linkAt(1);
while (Token::simpleMatch(tok2, "] ["))
tok2 = tok2->linkAt(1);
if (Token::Match(tok2, "] %assign%|++|--"))
break;
}
if (Token::Match(tok->previous(), "++|--|& %name%"))
break;
if (tok->variable() &&
!tok->variable()->isConst() &&
Token::Match(tok, "%name% . %name% (")) {
const Function* function = tok->tokAt(2)->function();
if (!function || !function->isConst())
break;
}
if (Token::Match(tok->previous(), "[(,] %name% [,)]") && isParameterChanged(tok))
break;
}
}
}
}
}
static std::string innerSmtString(const Token * tok)
{
if (!tok)
return "if";
if (!tok->astTop())
return "if";
const Token * top = tok->astTop();
if (top->str() == "(" && top->astOperand1())
return top->astOperand1()->str();
return top->str();
}
void CheckCondition::oppositeInnerConditionError(const Token *tok1, const Token* tok2, ErrorPath errorPath)
{
if (diag(tok1) & diag(tok2))
return;
const std::string s1(tok1 ? tok1->expressionString() : "x");
const std::string s2(tok2 ? tok2->expressionString() : "!x");
const std::string innerSmt = innerSmtString(tok2);
errorPath.emplace_back(ErrorPathItem(tok1, "outer condition: " + s1));
errorPath.emplace_back(ErrorPathItem(tok2, "opposite inner condition: " + s2));
const std::string msg("Opposite inner '" + innerSmt + "' condition leads to a dead code block.\n"
"Opposite inner '" + innerSmt + "' condition leads to a dead code block (outer condition is '" + s1 + "' and inner condition is '" + s2 + "').");
reportError(errorPath, Severity::warning, "oppositeInnerCondition", msg, CWE398, Certainty::normal);
}
void CheckCondition::identicalInnerConditionError(const Token *tok1, const Token* tok2, ErrorPath errorPath)
{
if (diag(tok1) & diag(tok2))
return;
const std::string s1(tok1 ? tok1->expressionString() : "x");
const std::string s2(tok2 ? tok2->expressionString() : "x");
const std::string innerSmt = innerSmtString(tok2);
errorPath.emplace_back(ErrorPathItem(tok1, "outer condition: " + s1));
errorPath.emplace_back(ErrorPathItem(tok2, "identical inner condition: " + s2));
const std::string msg("Identical inner '" + innerSmt + "' condition is always true.\n"
"Identical inner '" + innerSmt + "' condition is always true (outer condition is '" + s1 + "' and inner condition is '" + s2 + "').");
reportError(errorPath, Severity::warning, "identicalInnerCondition", msg, CWE398, Certainty::normal);
}
void CheckCondition::identicalConditionAfterEarlyExitError(const Token *cond1, const Token* cond2, ErrorPath errorPath)
{
if (diag(cond1) & diag(cond2))
return;
const bool isReturnValue = cond2 && Token::simpleMatch(cond2->astParent(), "return");
const std::string cond(cond1 ? cond1->expressionString() : "x");
const std::string value = (cond2 && cond2->valueType() && cond2->valueType()->type == ValueType::Type::BOOL) ? "false" : "0";
errorPath.emplace_back(ErrorPathItem(cond1, "If condition '" + cond + "' is true, the function will return/exit"));
errorPath.emplace_back(ErrorPathItem(cond2, (isReturnValue ? "Returning identical expression '" : "Testing identical condition '") + cond + "'"));
reportError(errorPath,
Severity::warning,
"identicalConditionAfterEarlyExit",
isReturnValue
? ("Identical condition and return expression '" + cond + "', return value is always " + value)
: ("Identical condition '" + cond + "', second condition is always false"),
CWE398,
Certainty::normal);
}
//---------------------------------------------------------------------------
// if ((x != 1) || (x != 3)) // expression always true
// if ((x == 1) && (x == 3)) // expression always false
// if ((x < 1) && (x > 3)) // expression always false
// if ((x > 3) || (x < 10)) // expression always true
// if ((x > 5) && (x != 1)) // second comparison always true
//
// Check for suspect logic for an expression consisting of 2 comparison
// expressions with a shared variable and constants and a logical operator
// between them.
//
// Suggest a different logical operator when the logical operator between
// the comparisons is probably wrong.
//
// Inform that second comparison is always true when first comparison is true.
//---------------------------------------------------------------------------
static std::string invertOperatorForOperandSwap(std::string s)
{
if (s[0] == '<')
s[0] = '>';
else if (s[0] == '>')
s[0] = '<';
return s;
}
template <typename T>
static bool checkIntRelation(const std::string &op, const T value1, const T value2)
{
return (op == "==" && value1 == value2) ||
(op == "!=" && value1 != value2) ||
(op == ">" && value1 > value2) ||
(op == ">=" && value1 >= value2) ||
(op == "<" && value1 < value2) ||
(op == "<=" && value1 <= value2);
}
static bool checkFloatRelation(const std::string &op, const double value1, const double value2)
{
return (op == ">" && value1 > value2) ||
(op == ">=" && value1 >= value2) ||
(op == "<" && value1 < value2) ||
(op == "<=" && value1 <= value2);
}
template<class T>
T getvalue3(const T value1, const T value2)
{
const T min = std::min(value1, value2);
if (min== std::numeric_limits<T>::max())
return min;
else
return min+1; // see #5895
}
template<>
double getvalue3(const double value1, const double value2)
{
return (value1 + value2) / 2.0f;
}
template<class T>
static inline T getvalue(const int test, const T value1, const T value2)
{
// test:
// 1 => return value that is less than both value1 and value2
// 2 => return value1
// 3 => return value that is between value1 and value2
// 4 => return value2
// 5 => return value that is larger than both value1 and value2
switch (test) {
case 1:
return std::numeric_limits<T>::lowest();
case 2:
return value1;
case 3:
return getvalue3<T>(value1, value2);
case 4:
return value2;
case 5:
return std::numeric_limits<T>::max();
}
return 0;
}
static bool parseComparison(const Token *comp, bool *not1, std::string *op, std::string *value, const Token **expr, bool* inconclusive)
{
*not1 = false;
while (comp && comp->str() == "!") {
*not1 = !(*not1);
comp = comp->astOperand1();
}
if (!comp)
return false;
const Token* op1 = comp->astOperand1();
const Token* op2 = comp->astOperand2();
if (!comp->isComparisonOp() || !op1 || !op2) {
*op = "!=";
*value = "0";
*expr = comp;
} else if (op1->isLiteral()) {
if (op1->isExpandedMacro())
return false;
*op = invertOperatorForOperandSwap(comp->str());
if (op1->enumerator() && op1->enumerator()->value_known)
*value = MathLib::toString(op1->enumerator()->value);
else
*value = op1->str();
*expr = op2;
} else if (comp->astOperand2()->isLiteral()) {
if (op2->isExpandedMacro())
return false;
*op = comp->str();
if (op2->enumerator() && op2->enumerator()->value_known)
*value = MathLib::toString(op2->enumerator()->value);
else
*value = op2->str();
*expr = op1;
} else {
*op = "!=";
*value = "0";
*expr = comp;
}
*inconclusive = *inconclusive || ((*value)[0] == '\'' && !(*op == "!=" || *op == "=="));
// Only float and int values are currently handled
if (!MathLib::isInt(*value) && !MathLib::isFloat(*value) && (*value)[0] != '\'')
return false;
return true;
}
static std::string conditionString(bool not1, const Token *expr1, const std::string &op, const std::string &value1)
{
if (expr1->astParent()->isComparisonOp())