forked from danmar/cppcheck
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsimple.cpp
More file actions
3512 lines (2926 loc) · 132 KB
/
simple.cpp
File metadata and controls
3512 lines (2926 loc) · 132 KB
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-2014 Daniel Marjamäki and 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/>.
*/
//---------------------------------------------------------------------------
// Remove includes from the benchmark run
// Included files aren't found anyway
//#include "checkother.h"
//#include "mathlib.h"
//#include "symboldatabase.h"
//#include <cctype> // std::isupper
//#include <cmath> // fabs()
//#include <stack>
//---------------------------------------------------------------------------
// Register this check class (by creating a static instance of it)
namespace {
CheckOther instance;
}
//---------------------------------------------------------------------------
void CheckOther::checkIncrementBoolean()
{
if (!_settings->isEnabled("style"))
return;
for (const Token *tok = _tokenizer->tokens(); tok; tok = tok->next()) {
if (Token::Match(tok, "%var% ++")) {
if (tok->varId()) {
const Token *declTok = Token::findmatch(_tokenizer->tokens(), "bool %varid%", tok->varId());
if (declTok)
incrementBooleanError(tok);
}
}
}
}
void CheckOther::incrementBooleanError(const Token *tok)
{
reportError(
tok,
Severity::style,
"incrementboolean",
"The use of a variable of type bool with the ++ postfix operator is always true and deprecated by the C++ Standard.\n"
"The operand of a postfix increment operator may be of type bool but it is deprecated by C++ Standard (Annex D-1) and the operand is always set to true\n"
);
}
//---------------------------------------------------------------------------
void CheckOther::clarifyCalculation()
{
if (!_settings->isEnabled("style"))
return;
for (const Token *tok = _tokenizer->tokens(); tok; tok = tok->next()) {
if (tok->strAt(1) == "?") {
// condition
const Token *cond = tok;
if (cond->isName() || cond->isNumber())
cond = cond->previous();
else if (cond->str() == ")")
cond = cond->link()->previous();
else
continue;
// calculation
if (!cond->isArithmeticalOp())
continue;
const std::string &op = cond->str();
cond = cond->previous();
// skip previous multiplications..
while (cond && cond->strAt(-1) == "*" && (cond->isName() || cond->isNumber()))
cond = cond->tokAt(-2);
if (!cond)
continue;
// first multiplication operand
if (cond->str() == ")") {
clarifyCalculationError(cond, op);
} else if (cond->isName() || cond->isNumber()) {
if (Token::Match(cond->previous(),("return|=|+|-|,|(|"+op).c_str()))
clarifyCalculationError(cond, op);
}
}
}
}
void CheckOther::clarifyCalculationError(const Token *tok, const std::string &op)
{
// suspicious calculation
const std::string calc("'a" + op + "b?c:d'");
// recommended calculation #1
const std::string s1("'(a" + op + "b)?c:d'");
// recommended calculation #2
const std::string s2("'a" + op + "(b?c:d)'");
reportError(tok,
Severity::style,
"clarifyCalculation",
"Clarify calculation precedence for " + op + " and ?\n"
"Suspicious calculation. Please use parentheses to clarify the code. "
"The code " + calc + " should be written as either " + s1 + " or " + s2 + ".");
}
// Clarify condition '(x = a < 0)' into '((x = a) < 0)' or '(x = (a < 0))'
void CheckOther::clarifyCondition()
{
if (!_settings->isEnabled("style"))
return;
for (const Token *tok = _tokenizer->tokens(); tok; tok = tok->next()) {
if (Token::Match(tok, "( %var% =")) {
for (const Token *tok2 = tok->tokAt(2); tok2; tok2 = tok2->next()) {
if (tok2->str() == "(" || tok2->str() == "[")
tok2 = tok2->link();
else if (Token::Match(tok2, "&&|%oror%|?|)"))
break;
else if (Token::Match(tok2, "<|<=|==|!=|>|>= %num% )")) {
clarifyConditionError(tok);
break;
}
}
}
}
}
void CheckOther::clarifyConditionError(const Token *tok)
{
reportError(tok,
Severity::style,
"clarifyCondition",
"Suspicious condition (assignment+comparison), it can be clarified with parentheses");
}
void CheckOther::warningOldStylePointerCast()
{
if (!_settings->isEnabled("style") ||
(_tokenizer->tokens() && _tokenizer->fileLine(_tokenizer->tokens()).find(".cpp") == std::string::npos))
return;
for (const Token *tok = _tokenizer->tokens(); tok; tok = tok->next()) {
// Old style pointer casting..
if (!Token::Match(tok, "( const| %type% * ) %var%") &&
!Token::Match(tok, "( const| %type% * ) (| new"))
continue;
int addToIndex = 0;
if (tok->tokAt(1)->str() == "const")
addToIndex = 1;
if (tok->tokAt(4 + addToIndex)->str() == "const")
continue;
// Is "type" a class?
const std::string pattern("class " + tok->tokAt(1 + addToIndex)->str());
if (!Token::findmatch(_tokenizer->tokens(), pattern.c_str()))
continue;
cstyleCastError(tok);
}
}
//---------------------------------------------------------------------------
// fflush(stdin) <- fflush only applies to output streams in ANSI C
//---------------------------------------------------------------------------
void CheckOther::checkFflushOnInputStream()
{
const Token *tok = _tokenizer->tokens();
while (tok && ((tok = Token::findsimplematch(tok, "fflush ( stdin )")) != NULL)) {
fflushOnInputStreamError(tok, tok->strAt(2));
tok = tok->tokAt(4);
}
}
void CheckOther::checkSizeofForNumericParameter()
{
for (const Token *tok = _tokenizer->tokens(); tok; tok = tok->next()) {
if (Token::Match(tok, "sizeof ( %num% )")
|| Token::Match(tok, "sizeof ( - %num% )")
|| Token::Match(tok, "sizeof %num%")
|| Token::Match(tok, "sizeof - %num%")
) {
sizeofForNumericParameterError(tok);
}
}
}
void CheckOther::checkSizeofForArrayParameter()
{
for (const Token *tok = _tokenizer->tokens(); tok; tok = tok->next()) {
if (Token::Match(tok, "sizeof ( %var% )") || Token::Match(tok, "sizeof %var%")) {
int tokIdx = 1;
if (tok->tokAt(tokIdx)->str() == "(") {
++tokIdx;
}
if (tok->tokAt(tokIdx)->varId() > 0) {
const Token *declTok = Token::findmatch(_tokenizer->tokens(), "%varid%", tok->tokAt(tokIdx)->varId());
if (declTok) {
if (Token::simpleMatch(declTok->next(), "[")) {
declTok = declTok->next()->link();
// multidimensional array
while (Token::simpleMatch(declTok->next(), "[")) {
declTok = declTok->next()->link();
}
if (!(Token::Match(declTok->next(), "= %str%")) && !(Token::simpleMatch(declTok->next(), "= {")) && !(Token::simpleMatch(declTok->next(), ";"))) {
if (Token::simpleMatch(declTok->next(), ",")) {
declTok = declTok->next();
while (!Token::simpleMatch(declTok, ";")) {
if (Token::simpleMatch(declTok, ")")) {
sizeofForArrayParameterError(tok);
break;
}
if (Token::Match(declTok, "(|[|{")) {
declTok = declTok->link();
}
declTok = declTok->next();
}
}
}
if (Token::simpleMatch(declTok->next(), ")")) {
sizeofForArrayParameterError(tok);
}
}
}
}
}
}
}
//---------------------------------------------------------------------------
// switch (x)
// {
// case 2:
// y = a; // <- this assignment is redundant
// case 3:
// y = b; // <- case 2 falls through and sets y twice
// }
//---------------------------------------------------------------------------
void CheckOther::checkRedundantAssignmentInSwitch()
{
const char switchPattern[] = "switch ( %any% ) { case";
const char breakPattern[] = "break|continue|return|exit|goto|throw";
const char functionPattern[] = "%var% (";
// Find the beginning of a switch. E.g.:
// switch (var) { ...
const Token *tok = Token::findmatch(_tokenizer->tokens(), switchPattern);
while (tok) {
// Check the contents of the switch statement
std::map<unsigned int, const Token*> varsAssigned;
int indentLevel = 0;
for (const Token *tok2 = tok->tokAt(5); tok2; tok2 = tok2->next()) {
if (tok2->str() == "{") {
// Inside a conditional or loop. Don't mark variable accesses as being redundant. E.g.:
// case 3: b = 1;
// case 4: if (a) { b = 2; } // Doesn't make the b=1 redundant because it's conditional
if (Token::Match(tok2->previous(), ")|else {") && tok2->link()) {
const Token* endOfConditional = tok2->link();
for (const Token* tok3 = tok2; tok3 != endOfConditional; tok3 = tok3->next()) {
if (tok3->varId() != 0)
varsAssigned.erase(tok3->varId());
else if (Token::Match(tok3, functionPattern) || Token::Match(tok3, breakPattern))
varsAssigned.clear();
}
tok2 = endOfConditional;
} else
++ indentLevel;
} else if (tok2->str() == "}") {
-- indentLevel;
// End of the switch block
if (indentLevel < 0)
break;
}
// Variable assignment. Report an error if it's assigned to twice before a break. E.g.:
// case 3: b = 1; // <== redundant
// case 4: b = 2;
if (Token::Match(tok2->previous(), ";|{|}|: %var% = %any% ;") && tok2->varId() != 0) {
std::map<unsigned int, const Token*>::iterator i = varsAssigned.find(tok2->varId());
if (i == varsAssigned.end())
varsAssigned[tok2->varId()] = tok2;
else
redundantAssignmentInSwitchError(i->second, i->second->str());
}
// Not a simple assignment so there may be good reason if this variable is assigned to twice. E.g.:
// case 3: b = 1;
// case 4: b++;
else if (tok2->varId() != 0)
varsAssigned.erase(tok2->varId());
// Reset our record of assignments if there is a break or function call. E.g.:
// case 3: b = 1; break;
if (Token::Match(tok2, functionPattern) || Token::Match(tok2, breakPattern))
varsAssigned.clear();
}
tok = Token::findmatch(tok->next(), switchPattern);
}
}
void CheckOther::checkSwitchCaseFallThrough()
{
if (!(_settings->isEnabled("style") && _settings->experimental))
return;
const char switchPattern[] = "switch (";
const char breakPattern[] = "break|continue|return|exit|goto|throw";
// Find the beginning of a switch. E.g.:
// switch (var) { ...
const Token *tok = Token::findmatch(_tokenizer->tokens(), switchPattern);
while (tok) {
// Check the contents of the switch statement
std::stack<std::pair<Token *, bool> > ifnest;
std::stack<Token *> loopnest;
std::stack<Token *> scopenest;
bool justbreak = true;
bool firstcase = true;
for (const Token *tok2 = tok->tokAt(1)->link()->tokAt(2); tok2; tok2 = tok2->next()) {
if (Token::simpleMatch(tok2, "if (")) {
tok2 = tok2->tokAt(1)->link()->next();
if (tok2->link() == NULL) {
std::ostringstream errmsg;
errmsg << "unmatched if in switch: " << tok2->linenr();
reportError(_tokenizer->tokens(), Severity::debug, "debug", errmsg.str());
break;
}
ifnest.push(std::make_pair(tok2->link(), false));
justbreak = false;
} else if (Token::simpleMatch(tok2, "while (")) {
tok2 = tok2->tokAt(1)->link()->next();
// skip over "do { } while ( ) ;" case
if (tok2->str() == "{") {
if (tok2->link() == NULL) {
std::ostringstream errmsg;
errmsg << "unmatched while in switch: " << tok2->linenr();
reportError(_tokenizer->tokens(), Severity::debug, "debug", errmsg.str());
break;
}
loopnest.push(tok2->link());
}
justbreak = false;
} else if (Token::simpleMatch(tok2, "do {")) {
tok2 = tok2->tokAt(1);
if (tok2->link() == NULL) {
std::ostringstream errmsg;
errmsg << "unmatched do in switch: " << tok2->linenr();
reportError(_tokenizer->tokens(), Severity::debug, "debug", errmsg.str());
break;
}
loopnest.push(tok2->link());
justbreak = false;
} else if (Token::simpleMatch(tok2, "for (")) {
tok2 = tok2->tokAt(1)->link()->next();
if (tok2->link() == NULL) {
std::ostringstream errmsg;
errmsg << "unmatched for in switch: " << tok2->linenr();
reportError(_tokenizer->tokens(), Severity::debug, "debug", errmsg.str());
break;
}
loopnest.push(tok2->link());
justbreak = false;
} else if (Token::Match(tok2, switchPattern)) {
// skip over nested switch, we'll come to that soon
tok2 = tok2->tokAt(1)->link()->next()->link();
} else if (Token::Match(tok2, breakPattern)) {
if (loopnest.empty()) {
justbreak = true;
}
tok2 = Token::findsimplematch(tok2, ";");
} else if (Token::Match(tok2, "case|default")) {
if (!justbreak && !firstcase) {
switchCaseFallThrough(tok2);
}
tok2 = Token::findsimplematch(tok2, ":");
justbreak = true;
firstcase = false;
} else if (tok2->str() == "{") {
scopenest.push(tok2->link());
} else if (tok2->str() == "}") {
if (!ifnest.empty() && tok2 == ifnest.top().first) {
if (tok2->next()->str() == "else") {
tok2 = tok2->tokAt(2);
ifnest.pop();
if (tok2->link() == NULL) {
std::ostringstream errmsg;
errmsg << "unmatched if in switch: " << tok2->linenr();
reportError(_tokenizer->tokens(), Severity::debug, "debug", errmsg.str());
break;
}
ifnest.push(std::make_pair(tok2->link(), justbreak));
justbreak = false;
} else {
justbreak &= ifnest.top().second;
ifnest.pop();
}
} else if (!loopnest.empty() && tok2 == loopnest.top()) {
loopnest.pop();
} else if (!scopenest.empty() && tok2 == scopenest.top()) {
scopenest.pop();
} else {
if (!ifnest.empty() || !loopnest.empty() || !scopenest.empty()) {
std::ostringstream errmsg;
errmsg << "unexpected end of switch: ";
errmsg << "ifnest=" << ifnest.size();
if (!ifnest.empty())
errmsg << "," << ifnest.top().first->linenr();
errmsg << ", loopnest=" << loopnest.size();
if (!loopnest.empty())
errmsg << "," << loopnest.top()->linenr();
errmsg << ", scopenest=" << scopenest.size();
if (!scopenest.empty())
errmsg << "," << scopenest.top()->linenr();
reportError(_tokenizer->tokens(), Severity::debug, "debug", errmsg.str());
}
// end of switch block
break;
}
} else if (tok2->str() != ";") {
justbreak = false;
}
}
tok = Token::findmatch(tok->next(), switchPattern);
}
}
//---------------------------------------------------------------------------
// int x = 1;
// x = x; // <- redundant assignment to self
//
// int y = y; // <- redundant initialization to self
//---------------------------------------------------------------------------
void CheckOther::checkSelfAssignment()
{
if (!_settings->isEnabled("style"))
return;
// POD variables..
std::set<unsigned int> pod;
for (const Token *tok = _tokenizer->tokens(); tok; tok = tok->next()) {
if (tok->isStandardType() && Token::Match(tok->tokAt(2), "[,);]") && tok->next()->varId())
pod.insert(tok->next()->varId());
}
const char selfAssignmentPattern[] = "%var% = %var% ;|=|)";
const Token *tok = Token::findmatch(_tokenizer->tokens(), selfAssignmentPattern);
while (tok) {
if (Token::Match(tok->previous(), "[;{}]") &&
tok->varId() && tok->varId() == tok->tokAt(2)->varId() &&
pod.find(tok->varId()) != pod.end()) {
selfAssignmentError(tok, tok->str());
}
tok = Token::findmatch(tok->next(), selfAssignmentPattern);
}
}
//---------------------------------------------------------------------------
// int a = 1;
// assert(a = 2); // <- assert should not have a side-effect
//---------------------------------------------------------------------------
void CheckOther::checkAssignmentInAssert()
{
if (!_settings->isEnabled("style"))
return;
const char assertPattern[] = "assert ( %any%";
const Token *tok = Token::findmatch(_tokenizer->tokens(), assertPattern);
const Token *endTok = tok ? tok->next()->link() : NULL;
while (tok && endTok) {
const Token* varTok = Token::findmatch(tok->tokAt(2), "%var% --|++|+=|-=|*=|/=|&=|^=|=", endTok);
if (varTok) {
assignmentInAssertError(tok, varTok->str());
} else if (NULL != (varTok = Token::findmatch(tok->tokAt(2), "--|++ %var%", endTok))) {
assignmentInAssertError(tok, varTok->strAt(1));
}
tok = Token::findmatch(endTok->next(), assertPattern);
endTok = tok ? tok->next()->link() : NULL;
}
}
//---------------------------------------------------------------------------
// if ((x != 1) || (x != 3)) // <- always true
// if ((x == 1) && (x == 3)) // <- always false
// if ((x < 1) && (x > 3)) // <- always false
// if ((x > 3) || (x < 10)) // <- always true
//---------------------------------------------------------------------------
void CheckOther::checkIncorrectLogicOperator()
{
if (!_settings->isEnabled("style"))
return;
const char conditionPattern[] = "if|while (";
const Token *tok = Token::findmatch(_tokenizer->tokens(), conditionPattern);
const Token *endTok = tok ? tok->next()->link() : NULL;
while (tok && endTok) {
// Find a pair of OR'd terms, with or without parentheses
// e.g. if (x != 3 || x != 4)
const Token *logicTok = NULL, *term1Tok = NULL, *term2Tok = NULL;
const Token *op1Tok = NULL, *op2Tok = NULL, *op3Tok = NULL, *nextTok = NULL;
if (NULL != (logicTok = Token::findmatch(tok, "( %any% !=|==|<|>|>=|<= %any% ) &&|%oror% ( %any% !=|==|<|>|>=|<= %any% ) %any%", endTok))) {
term1Tok = logicTok->next();
term2Tok = logicTok->tokAt(7);
op1Tok = logicTok->tokAt(2);
op2Tok = logicTok->tokAt(5);
op3Tok = logicTok->tokAt(8);
nextTok = logicTok->tokAt(11);
} else if (NULL != (logicTok = Token::findmatch(tok, "%any% !=|==|<|>|>=|<= %any% &&|%oror% %any% !=|==|<|>|>=|<= %any% %any%", endTok))) {
term1Tok = logicTok;
term2Tok = logicTok->tokAt(4);
op1Tok = logicTok->tokAt(1);
op2Tok = logicTok->tokAt(3);
op3Tok = logicTok->tokAt(5);
nextTok = logicTok->tokAt(7);
}
if (logicTok) {
// Find the common variable and the two different-valued constants
unsigned int variableTested = 0;
std::string firstConstant, secondConstant;
bool varFirst1, varFirst2;
unsigned int varId;
if (Token::Match(term1Tok, "%var% %any% %num%")) {
varId = term1Tok->varId();
if (!varId) {
tok = Token::findmatch(endTok->next(), conditionPattern);
endTok = tok ? tok->next()->link() : NULL;
continue;
}
varFirst1 = true;
firstConstant = term1Tok->tokAt(2)->str();
} else if (Token::Match(term1Tok, "%num% %any% %var%")) {
varId = term1Tok->tokAt(2)->varId();
if (!varId) {
tok = Token::findmatch(endTok->next(), conditionPattern);
endTok = tok ? tok->next()->link() : NULL;
continue;
}
varFirst1 = false;
firstConstant = term1Tok->str();
} else {
tok = Token::findmatch(endTok->next(), conditionPattern);
endTok = tok ? tok->next()->link() : NULL;
continue;
}
if (Token::Match(term2Tok, "%var% %any% %num%")) {
const unsigned int varId2 = term2Tok->varId();
if (!varId2 || varId != varId2) {
tok = Token::findmatch(endTok->next(), conditionPattern);
endTok = tok ? tok->next()->link() : NULL;
continue;
}
varFirst2 = true;
secondConstant = term2Tok->tokAt(2)->str();
variableTested = varId;
} else if (Token::Match(term2Tok, "%num% %any% %var%")) {
const unsigned int varId2 = term1Tok->tokAt(2)->varId();
if (!varId2 || varId != varId2) {
tok = Token::findmatch(endTok->next(), conditionPattern);
endTok = tok ? tok->next()->link() : NULL;
continue;
}
varFirst2 = false;
secondConstant = term2Tok->str();
variableTested = varId;
} else {
tok = Token::findmatch(endTok->next(), conditionPattern);
endTok = tok ? tok->next()->link() : NULL;
continue;
}
if (variableTested == 0 || firstConstant.empty() || secondConstant.empty()) {
tok = Token::findmatch(endTok->next(), conditionPattern);
endTok = tok ? tok->next()->link() : NULL;
continue;
}
enum Position { First, Second, NA };
enum Relation { Equal, NotEqual, Less, LessEqual, More, MoreEqual };
struct Condition {
const char *before;
Position position1;
const char *op1TokStr;
const char *op2TokStr;
Position position2;
const char *op3TokStr;
const char *after;
Relation relation;
bool state;
} conditions[] = {
{ "!!&&", NA, "!=", "||", NA, "!=", "!!&&", NotEqual, true }, // (x != 1) || (x != 3) <- always true
{ "(", NA, "==", "&&", NA, "==", ")", NotEqual, false }, // (x == 1) && (x == 3) <- always false
{ "(", First, "<", "&&", First, ">", ")", LessEqual, false }, // (x < 1) && (x > 3) <- always false
{ "(", First, ">", "&&", First, "<", ")", MoreEqual, false }, // (x > 3) && (x < 1) <- always false
{ "(", Second, ">", "&&", First, ">", ")", LessEqual, false }, // (1 > x) && (x > 3) <- always false
{ "(", First, ">", "&&", Second, ">", ")", MoreEqual, false }, // (x > 3) && (1 > x) <- always false
{ "(", First, "<", "&&", Second, "<", ")", LessEqual, false }, // (x < 1) && (3 < x) <- always false
{ "(", Second, "<", "&&", First, "<", ")", MoreEqual, false }, // (3 < x) && (x < 1) <- always false
{ "(", Second, ">", "&&", Second, "<", ")", LessEqual, false }, // (1 > x) && (3 < x) <- always false
{ "(", Second, "<", "&&", Second, ">", ")", MoreEqual, false }, // (3 < x) && (1 > x) <- always false
{ "(", First , ">|>=", "||", First, "<|<=", ")", Less, true }, // (x > 3) || (x < 10) <- always true
{ "(", First , "<|<=", "||", First, ">|>=", ")", More, true }, // (x < 10) || (x > 3) <- always true
{ "(", Second, "<|<=", "||", First, "<|<=", ")", Less, true }, // (3 < x) || (x < 10) <- always true
{ "(", First, "<|<=", "||", Second, "<|<=", ")", More, true }, // (x < 10) || (3 < x) <- always true
{ "(", First, ">|>=", "||", Second, ">|>=", ")", Less, true }, // (x > 3) || (10 > x) <- always true
{ "(", Second, ">|>=", "||", First, ">|>=", ")", More, true }, // (10 > x) || (x > 3) <- always true
{ "(", Second, "<|<=", "||", Second, ">|<=", ")", Less, true }, // (3 < x) || (10 > x) <- always true
{ "(", Second, ">|>=", "||", Second, "<|<=", ")", More, true }, // (10 > x) || (3 < x) <- always true
};
for (unsigned int i = 0; i < (sizeof(conditions) / sizeof(conditions[0])); i++) {
if (!((conditions[i].position1 == NA) || (((conditions[i].position1 == First) && varFirst1) || ((conditions[i].position1 == Second) && !varFirst1))))
continue;
if (!((conditions[i].position2 == NA) || (((conditions[i].position2 == First) && varFirst2) || ((conditions[i].position2 == Second) && !varFirst2))))
continue;
if (!Token::Match(op1Tok, conditions[i].op1TokStr))
continue;
if (!Token::Match(op2Tok, conditions[i].op2TokStr))
continue;
if (!Token::Match(op3Tok, conditions[i].op3TokStr))
continue;
if (!Token::Match(logicTok->previous(), conditions[i].before))
continue;
if (!Token::Match(nextTok, conditions[i].after))
continue;
if ((conditions[i].relation == Equal && MathLib::isEqual(firstConstant, secondConstant)) ||
(conditions[i].relation == NotEqual && MathLib::isNotEqual(firstConstant, secondConstant)) ||
(conditions[i].relation == Less && MathLib::isLess(firstConstant, secondConstant)) ||
(conditions[i].relation == LessEqual && MathLib::isLessEqual(firstConstant, secondConstant)) ||
(conditions[i].relation == More && MathLib::isGreater(firstConstant, secondConstant)) ||
(conditions[i].relation == MoreEqual && MathLib::isGreaterEqual(firstConstant, secondConstant)))
incorrectLogicOperatorError(term1Tok, conditions[i].state);
}
}
tok = Token::findmatch(endTok->next(), conditionPattern);
endTok = tok ? tok->next()->link() : NULL;
}
}
//---------------------------------------------------------------------------
// try {} catch (std::exception err) {} <- Should be "std::exception& err"
//---------------------------------------------------------------------------
void CheckOther::checkCatchExceptionByValue()
{
if (!_settings->isEnabled("style"))
return;
const char catchPattern[] = "} catch (";
const Token *tok = Token::findmatch(_tokenizer->tokens(), catchPattern);
const Token *endTok = tok ? tok->tokAt(2)->link() : NULL;
while (tok && endTok) {
// Find a pass-by-value declaration in the catch(), excluding basic types
// e.g. catch (std::exception err)
const Token *tokType = Token::findmatch(tok, "%type% %var% )", endTok);
if (tokType && !tokType->isStandardType()) {
catchExceptionByValueError(tokType);
}
tok = Token::findmatch(endTok->next(), catchPattern);
endTok = tok ? tok->tokAt(2)->link() : NULL;
}
}
//---------------------------------------------------------------------------
// strtol(str, 0, radix) <- radix must be 0 or 2-36
//---------------------------------------------------------------------------
void CheckOther::invalidFunctionUsage()
{
// strtol and strtoul..
for (const Token *tok = _tokenizer->tokens(); tok; tok = tok->next()) {
if (!Token::Match(tok, "strtol|strtoul ("))
continue;
// Locate the third parameter of the function call..
int param = 1;
for (const Token *tok2 = tok->tokAt(2); tok2; tok2 = tok2->next()) {
if (tok2->str() == "(")
tok2 = tok2->link();
else if (tok2->str() == ")")
break;
else if (tok2->str() == ",") {
++param;
if (param == 3) {
if (Token::Match(tok2, ", %num% )")) {
const MathLib::bigint radix = MathLib::toLongNumber(tok2->next()->str());
if (!(radix == 0 || (radix >= 2 && radix <= 36))) {
dangerousUsageStrtolError(tok2);
}
}
break;
}
}
}
}
// sprintf|snprintf overlapping data
for (const Token *tok = _tokenizer->tokens(); tok; tok = tok->next()) {
// Get variable id of target buffer..
unsigned int varid = 0;
if (Token::Match(tok, "sprintf|snprintf ( %var% ,"))
varid = tok->tokAt(2)->varId();
else if (Token::Match(tok, "sprintf|snprintf ( %var% . %var% ,"))
varid = tok->tokAt(4)->varId();
if (varid == 0)
continue;
// goto ","
const Token *tok2 = tok->tokAt(3);
while (tok2 && tok2->str() != ",")
tok2 = tok2->next();
if (!tok2)
continue;
// is any source buffer overlapping the target buffer?
int parlevel = 0;
while ((tok2 = tok2->next()) != NULL) {
if (tok2->str() == "(")
++parlevel;
else if (tok2->str() == ")") {
--parlevel;
if (parlevel < 0)
break;
} else if (parlevel == 0 && Token::Match(tok2, ", %varid% [,)]", varid)) {
sprintfOverlappingDataError(tok2->next(), tok2->next()->str());
break;
}
}
}
}
//---------------------------------------------------------------------------
void CheckOther::invalidScanf()
{
if (!_settings->isEnabled("style"))
return;
for (const Token *tok = _tokenizer->tokens(); tok; tok = tok->next()) {
const Token *formatToken = 0;
if (Token::Match(tok, "scanf|vscanf ( %str% ,"))
formatToken = tok->tokAt(2);
else if (Token::Match(tok, "fscanf|vfscanf ( %var% , %str% ,"))
formatToken = tok->tokAt(4);
else
continue;
bool format = false;
// scan the string backwards, so we dont need to keep states
const std::string &formatstr(formatToken->str());
for (unsigned int i = 1; i < formatstr.length(); i++) {
if (formatstr[i] == '%')
format = !format;
else if (!format)
continue;
else if (std::isdigit(formatstr[i])) {
format = false;
}
else if (std::isalpha(formatstr[i])) {
invalidScanfError(tok);
format = false;
}
}
}
}
//---------------------------------------------------------------------------
// if (!x==3) <- Probably meant to be "x!=3"
//---------------------------------------------------------------------------
void CheckOther::checkComparisonOfBoolWithInt()
{
if (!_settings->isEnabled("style"))
return;
for (const Token *tok = _tokenizer->tokens(); tok; tok = tok->next()) {
if (Token::Match(tok, "( ! %var% ==|!= %num% )")) {
const Token *numTok = tok->tokAt(4);
if (numTok && numTok->str() != "0") {
comparisonOfBoolWithIntError(numTok, tok->strAt(2));
}
} else if (Token::Match(tok, "( %num% ==|!= ! %var% )")) {
const Token *numTok = tok->tokAt(1);
if (numTok && numTok->str() != "0") {
comparisonOfBoolWithIntError(numTok, tok->strAt(4));
}
}
}
}
//---------------------------------------------------------------------------
// switch (x)
// {
// case 2:
// y = a;
// break;
// break; // <- Redundant break
// case 3:
// y = b;
// }
//---------------------------------------------------------------------------
void CheckOther::checkDuplicateBreak()
{
if (!_settings->isEnabled("style"))
return;
const char breakPattern[] = "break|continue ; break|continue ;";
// Find consecutive break or continue statements. e.g.:
// break; break;
const Token *tok = Token::findmatch(_tokenizer->tokens(), breakPattern);
while (tok) {
duplicateBreakError(tok);
tok = Token::findmatch(tok->next(), breakPattern);
}
}
void CheckOther::sizeofForNumericParameterError(const Token *tok)
{
reportError(tok, Severity::error,
"sizeofwithnumericparameter", "Using sizeof with a numeric constant as function "
"argument might not be what you intended.\n"
"It is unusual to use constant value with sizeof. For example, this code:\n"
" int f() {\n"
" return sizeof(10);\n"
" }\n"
" returns 4 (in 32-bit systems) or 8 (in 64-bit systems) instead of 10."
);
}
void CheckOther::sizeofForArrayParameterError(const Token *tok)
{
reportError(tok, Severity::error,
"sizeofwithsilentarraypointer", "Using sizeof for array given as function argument "
"returns the size of pointer.\n"
"Giving array as function parameter and then using sizeof-operator for the array "
"argument. In this case the sizeof-operator returns the size of pointer (in the "
"system). It does not return the size of the whole array in bytes as might be "
"expected. For example, this code:\n"
" int f(char a[100]) {\n"
" return sizeof(a);\n"
" }\n"
" returns 4 (in 32-bit systems) or 8 (in 64-bit systems) instead of 100 (the "
"size of the array in bytes)."
);
}
void CheckOther::invalidScanfError(const Token *tok)
{
reportError(tok, Severity::warning,
"invalidscanf", "scanf without field width limits can crash with huge input data\n"
"scanf without field width limits can crash with huge input data. To fix this error "
"message add a field width specifier:\n"
" %s => %20s\n"
" %i => %3i\n"
"\n"
"Sample program that can crash:\n"
"\n"
"#include <stdio.h>\n"
"int main()\n"
"{\n"
" int a;\n"
" scanf(\"%i\", &a);\n"
" return 0;\n"
"}\n"
"\n"
"To make it crash:\n"
"perl -e 'print \"5\"x2100000' | ./a.out");
}
//---------------------------------------------------------------------------
// Check for unsigned divisions
//---------------------------------------------------------------------------
void CheckOther::checkUnsignedDivision()
{
if (!_settings->isEnabled("style"))
return;
// Check for "ivar / uvar" and "uvar / ivar"
std::map<unsigned int, char> varsign;
for (const Token *tok = _tokenizer->tokens(); tok; tok = tok->next()) {
if (Token::Match(tok, "[{};(,] %type% %var% [;=,)]")) {
if (tok->tokAt(1)->isUnsigned())
varsign[tok->tokAt(2)->varId()] = 'u';
else
varsign[tok->tokAt(2)->varId()] = 's';
}
else if (!Token::Match(tok, "[).]") && Token::Match(tok->next(), "%var% / %num%")) {
if (tok->strAt(3)[0] == '-') {
char sign1 = varsign[tok->tokAt(1)->varId()];
if (sign1 == 'u') {
udivError(tok->next());
}
}
}
else if (Token::Match(tok, "(|[|=|%op% %num% / %var%")) {
if (tok->strAt(1)[0] == '-') {
char sign2 = varsign[tok->tokAt(3)->varId()];
if (sign2 == 'u') {
udivError(tok->next());
}
}
}
}
}
//---------------------------------------------------------------------------
// memset(p, y, 0 /* bytes to fill */) <- 2nd and 3rd arguments inverted
//---------------------------------------------------------------------------
void CheckOther::checkMemsetZeroBytes()
{
const Token *tok = _tokenizer->tokens();
while (tok && ((tok = Token::findmatch(tok, "memset ( %var% , %num% , 0 )")) != NULL)) {
memsetZeroBytesError(tok, tok->strAt(2));
tok = tok->tokAt(8);
}
}
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
// Usage of function variables
//---------------------------------------------------------------------------
/**
* @brief This class is used to capture the control flow within a function.
*/
class ScopeInfo {
public:
ScopeInfo() : _token(NULL), _parent(NULL) { }
ScopeInfo(const Token *token, ScopeInfo *parent_) : _token(token), _parent(parent_) { }
~ScopeInfo();
ScopeInfo *parent() {
return _parent;
}
ScopeInfo *addChild(const Token *token);
void remove(ScopeInfo *scope);
private:
const Token *_token;
ScopeInfo *_parent;
std::list<ScopeInfo *> _children;