forked from danmar/cppcheck
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcheckother.cpp
More file actions
4825 lines (4346 loc) · 222 KB
/
checkother.cpp
File metadata and controls
4825 lines (4346 loc) · 222 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-2025 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/>.
*/
//---------------------------------------------------------------------------
#include "checkother.h"
#include "astutils.h"
#include "fwdanalysis.h"
#include "library.h"
#include "mathlib.h"
#include "platform.h"
#include "settings.h"
#include "standards.h"
#include "symboldatabase.h"
#include "token.h"
#include "tokenize.h"
#include "tokenlist.h"
#include "utils.h"
#include "valueflow.h"
#include "vfvalue.h"
#include <algorithm> // find_if()
#include <cassert>
#include <cctype>
#include <cstddef>
#include <cstdint>
#include <list>
#include <map>
#include <set>
#include <sstream>
#include <unordered_map>
#include <utility>
//---------------------------------------------------------------------------
// Register this check class (by creating a static instance of it)
namespace {
CheckOther instance;
}
static const CWE CWE128(128U); // Wrap-around Error
static const CWE CWE131(131U); // Incorrect Calculation of Buffer Size
static const CWE CWE197(197U); // Numeric Truncation Error
static const CWE CWE362(362U); // Concurrent Execution using Shared Resource with Improper Synchronization ('Race Condition')
static const CWE CWE369(369U); // Divide By Zero
static const CWE CWE398(398U); // Indicator of Poor Code Quality
static const CWE CWE475(475U); // Undefined Behavior for Input to API
static const CWE CWE561(561U); // Dead Code
static const CWE CWE563(563U); // Assignment to Variable without Use ('Unused Variable')
static const CWE CWE570(570U); // Expression is Always False
static const CWE CWE571(571U); // Expression is Always True
static const CWE CWE672(672U); // Operation on a Resource after Expiration or Release
static const CWE CWE628(628U); // Function Call with Incorrectly Specified Arguments
static const CWE CWE683(683U); // Function Call With Incorrect Order of Arguments
static const CWE CWE704(704U); // Incorrect Type Conversion or Cast
static const CWE CWE758(758U); // Reliance on Undefined, Unspecified, or Implementation-Defined Behavior
static const CWE CWE768(768U); // Incorrect Short Circuit Evaluation
static const CWE CWE783(783U); // Operator Precedence Logic Error
//----------------------------------------------------------------------------------
// The return value of fgetc(), getc(), ungetc(), getchar() etc. is an integer value.
// If this return value is stored in a character variable and then compared
// to EOF, which is an integer, the comparison maybe be false.
//
// Reference:
// - Ticket #160
// - http://www.cplusplus.com/reference/cstdio/fgetc/
// - http://www.cplusplus.com/reference/cstdio/getc/
// - http://www.cplusplus.com/reference/cstdio/getchar/
// - http://www.cplusplus.com/reference/cstdio/ungetc/ ...
//----------------------------------------------------------------------------------
void CheckOther::checkCastIntToCharAndBack()
{
if (!mSettings->severity.isEnabled(Severity::warning))
return;
logChecker("CheckOther::checkCastIntToCharAndBack"); // warning
const SymbolDatabase *symbolDatabase = mTokenizer->getSymbolDatabase();
for (const Scope * scope : symbolDatabase->functionScopes) {
std::map<int, std::string> vars;
for (const Token* tok = scope->bodyStart->next(); tok && tok != scope->bodyEnd; tok = tok->next()) {
// Quick check to see if any of the matches below have any chances
if (!Token::Match(tok, "%var%|EOF %comp%|="))
continue;
if (Token::Match(tok, "%var% = fclose|fflush|fputc|fputs|fscanf|getchar|getc|fgetc|putchar|putc|puts|scanf|sscanf|ungetc (")) {
const Variable *var = tok->variable();
if (var && var->typeEndToken()->str() == "char" && !var->typeEndToken()->isSigned()) {
vars[tok->varId()] = tok->strAt(2);
}
} else if (Token::Match(tok, "EOF %comp% ( %var% = fclose|fflush|fputc|fputs|fscanf|getchar|getc|fgetc|putchar|putc|puts|scanf|sscanf|ungetc (")) {
tok = tok->tokAt(3);
const Variable *var = tok->variable();
if (var && var->typeEndToken()->str() == "char" && !var->typeEndToken()->isSigned()) {
checkCastIntToCharAndBackError(tok, tok->strAt(2));
}
} else if (tok->isCpp() && (Token::Match(tok, "EOF %comp% ( %var% = std :: cin . get (") || Token::Match(tok, "EOF %comp% ( %var% = cin . get ("))) {
tok = tok->tokAt(3);
const Variable *var = tok->variable();
if (var && var->typeEndToken()->str() == "char" && !var->typeEndToken()->isSigned()) {
checkCastIntToCharAndBackError(tok, "cin.get");
}
} else if (tok->isCpp() && (Token::Match(tok, "%var% = std :: cin . get (") || Token::Match(tok, "%var% = cin . get ("))) {
const Variable *var = tok->variable();
if (var && var->typeEndToken()->str() == "char" && !var->typeEndToken()->isSigned()) {
vars[tok->varId()] = "cin.get";
}
} else if (Token::Match(tok, "%var% %comp% EOF")) {
if (vars.find(tok->varId()) != vars.end()) {
checkCastIntToCharAndBackError(tok, vars[tok->varId()]);
}
} else if (Token::Match(tok, "EOF %comp% %var%")) {
tok = tok->tokAt(2);
if (vars.find(tok->varId()) != vars.end()) {
checkCastIntToCharAndBackError(tok, vars[tok->varId()]);
}
}
}
}
}
void CheckOther::checkCastIntToCharAndBackError(const Token *tok, const std::string &strFunctionName)
{
reportError(
tok,
Severity::warning,
"checkCastIntToCharAndBack",
"$symbol:" + strFunctionName + "\n"
"Storing $symbol() return value in char variable and then comparing with EOF.\n"
"When saving $symbol() return value in char variable there is loss of precision. "
" When $symbol() returns EOF this value is truncated. Comparing the char "
"variable with EOF can have unexpected results. For instance a loop \"while (EOF != (c = $symbol());\" "
"loops forever on some compilers/platforms and on other compilers/platforms it will stop "
"when the file contains a matching character.", CWE197, Certainty::normal
);
}
//---------------------------------------------------------------------------
// Clarify calculation precedence for ternary operators.
//---------------------------------------------------------------------------
void CheckOther::clarifyCalculation()
{
if (!mSettings->severity.isEnabled(Severity::style) && !mSettings->isPremiumEnabled("clarifyCalculation"))
return;
logChecker("CheckOther::clarifyCalculation"); // style
const SymbolDatabase *symbolDatabase = mTokenizer->getSymbolDatabase();
for (const Scope * scope : symbolDatabase->functionScopes) {
for (const Token* tok = scope->bodyStart->next(); tok != scope->bodyEnd; tok = tok->next()) {
// ? operator where lhs is arithmetical expression
if (tok->str() != "?" || !tok->astOperand1() || !tok->astOperand1()->isCalculation())
continue;
if (!tok->astOperand1()->isArithmeticalOp() && tok->astOperand1()->tokType() != Token::eBitOp)
continue;
// non-pointer calculation in lhs and pointer in rhs => no clarification is needed
if (tok->astOperand1()->isBinaryOp() && Token::Match(tok->astOperand1(), "%or%|&|%|*|/") && tok->astOperand2()->valueType() && tok->astOperand2()->valueType()->pointer > 0)
continue;
// bit operation in lhs and char literals in rhs => probably no mistake
if (tok->astOperand1()->tokType() == Token::eBitOp && Token::Match(tok->astOperand2()->astOperand1(), "%char%") && Token::Match(tok->astOperand2()->astOperand2(), "%char%"))
continue;
// 2nd operand in lhs has known integer value => probably no mistake
if (tok->astOperand1()->isBinaryOp() && tok->astOperand1()->astOperand2()->hasKnownIntValue()) {
const Token *op = tok->astOperand1()->astOperand2();
if (op->isNumber())
continue;
if (op->valueType() && op->valueType()->isEnum())
continue;
}
// Is code clarified by parentheses already?
const Token *tok2 = tok->astOperand1();
for (; tok2; tok2 = tok2->next()) {
if (tok2->str() == "(")
tok2 = tok2->link();
else if (tok2->str() == ")")
break;
else if (tok2->str() == "?") {
clarifyCalculationError(tok, tok->astOperand1()->str());
break;
}
}
}
}
}
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 + "'.", CWE783, Certainty::normal);
}
//---------------------------------------------------------------------------
// Clarify (meaningless) statements like *foo++; with parentheses.
//---------------------------------------------------------------------------
void CheckOther::clarifyStatement()
{
if (!mSettings->severity.isEnabled(Severity::warning))
return;
logChecker("CheckOther::clarifyStatement"); // warning
const SymbolDatabase *symbolDatabase = mTokenizer->getSymbolDatabase();
for (const Scope * scope : symbolDatabase->functionScopes) {
for (const Token* tok = scope->bodyStart; tok && tok != scope->bodyEnd; tok = tok->next()) {
if (tok->astOperand1() && Token::Match(tok, "* %name%")) {
const Token *tok2 = tok->previous();
while (tok2 && tok2->str() == "*")
tok2 = tok2->previous();
if (tok2 && !tok2->astParent() && Token::Match(tok2, "[{};]")) {
tok2 = tok->astOperand1();
if (Token::Match(tok2, "++|-- [;,]"))
clarifyStatementError(tok2);
}
}
}
}
}
void CheckOther::clarifyStatementError(const Token *tok)
{
reportError(tok, Severity::warning, "clarifyStatement", "In expression like '*A++' the result of '*' is unused. Did you intend to write '(*A)++;'?\n"
"A statement like '*A++;' might not do what you intended. Postfix 'operator++' is executed before 'operator*'. "
"Thus, the dereference is meaningless. Did you intend to write '(*A)++;'?", CWE783, Certainty::normal);
}
//---------------------------------------------------------------------------
// Check for suspicious occurrences of 'if(); {}'.
//---------------------------------------------------------------------------
void CheckOther::checkSuspiciousSemicolon()
{
if (!mSettings->certainty.isEnabled(Certainty::inconclusive) || !mSettings->severity.isEnabled(Severity::warning))
return;
const SymbolDatabase* const symbolDatabase = mTokenizer->getSymbolDatabase();
logChecker("CheckOther::checkSuspiciousSemicolon"); // warning,inconclusive
// Look for "if(); {}", "for(); {}" or "while(); {}"
for (const Scope &scope : symbolDatabase->scopeList) {
if (scope.type == ScopeType::eIf || scope.type == ScopeType::eElse || scope.type == ScopeType::eWhile || scope.type == ScopeType::eFor) {
// Ensure the semicolon is at the same line number as the if/for/while statement
// and the {..} block follows it without an extra empty line.
if (Token::simpleMatch(scope.bodyStart, "{ ; } {") &&
scope.bodyStart->previous()->linenr() == scope.bodyStart->tokAt(2)->linenr() &&
scope.bodyStart->linenr()+1 >= scope.bodyStart->tokAt(3)->linenr() &&
!scope.bodyStart->tokAt(3)->isExpandedMacro()) {
suspiciousSemicolonError(scope.classDef);
}
}
}
}
void CheckOther::suspiciousSemicolonError(const Token* tok)
{
reportError(tok, Severity::warning, "suspiciousSemicolon",
"Suspicious use of ; at the end of '" + (tok ? tok->str() : std::string()) + "' statement.", CWE398, Certainty::normal);
}
/** @brief would it make sense to use dynamic_cast instead of C style cast? */
static bool isDangerousTypeConversion(const Token* const tok)
{
const Token* from = tok->astOperand1();
if (!from)
return false;
if (!tok->valueType() || !from->valueType())
return false;
if (tok->valueType()->typeScope != nullptr &&
tok->valueType()->typeScope == from->valueType()->typeScope)
return false;
if (tok->valueType()->type == from->valueType()->type &&
tok->valueType()->isPrimitive())
return false;
// cast from derived object to base object is safe..
if (tok->valueType()->typeScope && from->valueType()->typeScope) {
const Type* fromType = from->valueType()->typeScope->definedType;
const Type* toType = tok->valueType()->typeScope->definedType;
if (fromType && toType && fromType->isDerivedFrom(toType->name()))
return false;
}
const bool refcast = (tok->valueType()->reference != Reference::None);
if (!refcast && tok->valueType()->pointer == 0)
return false;
if (!refcast && from->valueType()->pointer == 0)
return false;
if (tok->valueType()->type == ValueType::Type::VOID || from->valueType()->type == ValueType::Type::VOID)
return false;
if (tok->valueType()->pointer == 0 && tok->valueType()->isIntegral())
// ok: (uintptr_t)ptr;
return false;
if (from->valueType()->pointer == 0 && from->valueType()->isIntegral())
// ok: (int *)addr;
return false;
return true;
}
//---------------------------------------------------------------------------
// For C++ code, warn if C-style casts are used on pointer types
//---------------------------------------------------------------------------
void CheckOther::warningOldStylePointerCast()
{
// Only valid on C++ code
if (!mTokenizer->isCPP())
return;
if (!mSettings->severity.isEnabled(Severity::style) && !mSettings->isPremiumEnabled("cstyleCast"))
return;
logChecker("CheckOther::warningOldStylePointerCast"); // style,c++
const SymbolDatabase *symbolDatabase = mTokenizer->getSymbolDatabase();
for (const Scope * scope : symbolDatabase->functionScopes) {
const Token* tok;
if (scope->function && scope->function->isConstructor())
tok = scope->classDef;
else
tok = scope->bodyStart;
for (; tok && tok != scope->bodyEnd; tok = tok->next()) {
// Old style pointer casting..
if (!tok->isCast() || tok->isBinaryOp())
continue;
if (isDangerousTypeConversion(tok))
continue;
const Token* const errtok = tok;
const Token* castTok = tok->next();
while (Token::Match(castTok, "const|volatile|class|struct|union|%type%|::")) {
castTok = castTok->next();
if (Token::simpleMatch(castTok, "<") && castTok->link())
castTok = castTok->link()->next();
}
if (castTok == tok->next())
continue;
bool isPtr = false, isRef = false;
while (Token::Match(castTok, "*|const|&")) {
if (castTok->str() == "*")
isPtr = true;
else if (castTok->str() == "&")
isRef = true;
castTok = castTok->next();
}
if ((!isPtr && !isRef) || !Token::Match(castTok, ") (| %name%|%bool%|%char%|%str%|&"))
continue;
if (Token::Match(tok->previous(), "%type%"))
continue;
// skip first "const" in "const Type* const"
while (Token::Match(tok->next(), "const|volatile|class|struct|union"))
tok = tok->next();
const Token* typeTok = tok->next();
// skip second "const" in "const Type* const"
if (tok->strAt(3) == "const")
tok = tok->next();
const Token *p = tok->tokAt(4);
if (p->hasKnownIntValue() && p->getKnownIntValue()==0) // Casting nullpointers is safe
continue;
if (typeTok->tokType() == Token::eType || typeTok->tokType() == Token::eName)
cstyleCastError(errtok, isPtr);
}
}
}
void CheckOther::cstyleCastError(const Token *tok, bool isPtr)
{
const std::string type = isPtr ? "pointer" : "reference";
reportError(tok, Severity::style, "cstyleCast",
"C-style " + type + " casting\n"
"C-style " + type + " casting detected. C++ offers four different kinds of casts as replacements: "
"static_cast, const_cast, dynamic_cast and reinterpret_cast. A C-style cast could evaluate to "
"any of those automatically, thus it is considered safer if the programmer explicitly states "
"which kind of cast is expected.", CWE398, Certainty::normal);
}
void CheckOther::warningDangerousTypeCast()
{
// Only valid on C++ code
if (!mTokenizer->isCPP())
return;
if (!mSettings->severity.isEnabled(Severity::warning) && !mSettings->isPremiumEnabled("cstyleCast"))
return;
logChecker("CheckOther::warningDangerousTypeCast"); // warning,c++
const SymbolDatabase *symbolDatabase = mTokenizer->getSymbolDatabase();
for (const Scope * scope : symbolDatabase->functionScopes) {
const Token* tok;
if (scope->function && scope->function->isConstructor())
tok = scope->classDef;
else
tok = scope->bodyStart;
for (; tok && tok != scope->bodyEnd; tok = tok->next()) {
// Old style pointer casting..
if (!tok->isCast() || tok->isBinaryOp())
continue;
if (isDangerousTypeConversion(tok))
dangerousTypeCastError(tok, tok->valueType()->pointer > 0);
}
}
}
void CheckOther::dangerousTypeCastError(const Token *tok, bool isPtr)
{
//const std::string type = isPtr ? "pointer" : "reference";
(void)isPtr;
reportError(tok, Severity::warning, "dangerousTypeCast",
"Potentially invalid type conversion in old-style C cast, clarify/fix with C++ cast",
CWE398, Certainty::normal);
}
void CheckOther::warningIntToPointerCast()
{
if (!mSettings->severity.isEnabled(Severity::portability) && !mSettings->isPremiumEnabled("cstyleCast"))
return;
logChecker("CheckOther::warningIntToPointerCast"); // portability
for (const Token* tok = mTokenizer->tokens(); tok; tok = tok->next()) {
// pointer casting..
if (!tok->isCast())
continue;
const Token* from = tok->astOperand2() ? tok->astOperand2() : tok->astOperand1();
if (!from || !from->isNumber())
continue;
if (!tok->valueType() || tok->valueType()->pointer == 0)
continue;
if (!MathLib::isIntHex(from->str()) && from->hasKnownIntValue() && from->getKnownIntValue() != 0) {
std::string format;
if (MathLib::isDec(from->str()))
format = "decimal";
else if (MathLib::isOct(from->str()))
format = "octal";
else
continue;
intToPointerCastError(tok, format);
}
}
}
void CheckOther::intToPointerCastError(const Token *tok, const std::string& format)
{
reportError(tok, Severity::portability, "intToPointerCast",
"Casting non-zero " + format + " integer literal to pointer.",
CWE398, Certainty::normal);
}
void CheckOther::suspiciousFloatingPointCast()
{
if (!mSettings->severity.isEnabled(Severity::style) && !mSettings->isPremiumEnabled("suspiciousFloatingPointCast"))
return;
logChecker("CheckOther::suspiciousFloatingPointCast"); // style
const SymbolDatabase *symbolDatabase = mTokenizer->getSymbolDatabase();
for (const Scope * scope : symbolDatabase->functionScopes) {
const Token* tok = scope->bodyStart;
if (scope->function && scope->function->isConstructor())
tok = scope->classDef;
for (; tok && tok != scope->bodyEnd; tok = tok->next()) {
if (!tok->isCast())
continue;
const ValueType* vt = tok->valueType();
if (!vt || vt->pointer || vt->reference != Reference::None || (vt->type != ValueType::FLOAT && vt->type != ValueType::DOUBLE))
continue;
using VTT = std::vector<ValueType::Type>;
const VTT sourceTypes = vt->type == ValueType::FLOAT ? VTT{ ValueType::DOUBLE, ValueType::LONGDOUBLE } : VTT{ ValueType::LONGDOUBLE };
const Token* source = tok->astOperand2() ? tok->astOperand2() : tok->astOperand1();
if (!source || !source->valueType() || std::find(sourceTypes.begin(), sourceTypes.end(), source->valueType()->type) == sourceTypes.end())
continue;
const Token* parent = tok->astParent();
if (!parent)
continue;
const ValueType* parentVt = parent->valueType();
if (!parentVt || parent->str() == "(") {
int argn{};
if (const Token* ftok = getTokenArgumentFunction(tok, argn)) {
if (ftok->function()) {
if (const Variable* argVar = ftok->function()->getArgumentVar(argn))
parentVt = argVar->valueType();
}
}
}
if (!parentVt || std::find(sourceTypes.begin(), sourceTypes.end(), parentVt->type) == sourceTypes.end())
continue;
suspiciousFloatingPointCastError(tok);
}
}
}
void CheckOther::suspiciousFloatingPointCastError(const Token* tok)
{
reportError(tok, Severity::style, "suspiciousFloatingPointCast",
"Floating-point cast causes loss of precision.\n"
"If this cast is not intentional, remove it to avoid loss of precision", CWE398, Certainty::normal);
}
//---------------------------------------------------------------------------
// float* f; double* d = (double*)f; <-- Pointer cast to a type with an incompatible binary data representation
//---------------------------------------------------------------------------
void CheckOther::invalidPointerCast()
{
if (!mSettings->severity.isEnabled(Severity::portability))
return;
logChecker("CheckOther::invalidPointerCast"); // portability
const bool printInconclusive = mSettings->certainty.isEnabled(Certainty::inconclusive);
const SymbolDatabase* const symbolDatabase = mTokenizer->getSymbolDatabase();
for (const Scope * scope : symbolDatabase->functionScopes) {
for (const Token* tok = scope->bodyStart->next(); tok != scope->bodyEnd; tok = tok->next()) {
const Token* toTok = nullptr;
const Token* fromTok = nullptr;
// Find cast
if (Token::Match(tok, "( const|volatile| const|volatile| %type% %type%| const| * )")) {
toTok = tok;
fromTok = tok->astOperand1();
} else if (Token::simpleMatch(tok, "reinterpret_cast <") && tok->linkAt(1)) {
toTok = tok->linkAt(1)->next();
fromTok = toTok->astOperand2();
}
if (!fromTok)
continue;
const ValueType* fromType = fromTok->valueType();
const ValueType* toType = toTok->valueType();
if (!fromType || !toType || !fromType->pointer || !toType->pointer)
continue;
if (fromType->type != toType->type && fromType->type >= ValueType::Type::BOOL && toType->type >= ValueType::Type::BOOL && (toType->type != ValueType::Type::CHAR || printInconclusive)) {
if (toType->isIntegral() && fromType->isIntegral())
continue;
invalidPointerCastError(tok, fromType->str(), toType->str(), toType->type == ValueType::Type::CHAR, toType->isIntegral());
}
}
}
}
void CheckOther::invalidPointerCastError(const Token* tok, const std::string& from, const std::string& to, bool inconclusive, bool toIsInt)
{
if (toIsInt) { // If we cast something to int*, this can be useful to play with its binary data representation
reportError(tok, Severity::portability, "invalidPointerCast", "Casting from " + from + " to " + to + " is not portable due to different binary data representations on different platforms.", CWE704, inconclusive ? Certainty::inconclusive : Certainty::normal);
} else
reportError(tok, Severity::portability, "invalidPointerCast", "Casting between " + from + " and " + to + " which have an incompatible binary data representation.", CWE704, Certainty::normal);
}
//---------------------------------------------------------------------------
// Detect redundant assignments: x = 0; x = 4;
//---------------------------------------------------------------------------
void CheckOther::checkRedundantAssignment()
{
if (!mSettings->severity.isEnabled(Severity::style) &&
!mSettings->isPremiumEnabled("redundantAssignment") &&
!mSettings->isPremiumEnabled("redundantAssignInSwitch"))
return;
logChecker("CheckOther::checkRedundantAssignment"); // style
const SymbolDatabase* symbolDatabase = mTokenizer->getSymbolDatabase();
for (const Scope *scope : symbolDatabase->functionScopes) {
if (!scope->bodyStart)
continue;
for (const Token* tok = scope->bodyStart->next(); tok != scope->bodyEnd; tok = tok->next()) {
if (Token::simpleMatch(tok, "] ("))
// todo: handle lambdas
break;
if (Token::simpleMatch(tok, "try {"))
// todo: check try blocks
tok = tok->linkAt(1);
if ((tok->isAssignmentOp() || tok->tokType() == Token::eIncDecOp) && tok->astOperand1()) {
if (tok->astParent())
continue;
// Do not warn about redundant initialization when rhs is trivial
// TODO : do not simplify the variable declarations
bool isInitialization = false;
if (Token::Match(tok->tokAt(-2), "; %var% =") && tok->tokAt(-2)->isSplittedVarDeclEq()) {
isInitialization = true;
bool trivial = true;
visitAstNodes(tok->astOperand2(),
[&](const Token *rhs) {
if (Token::simpleMatch(rhs, "{ 0 }"))
return ChildrenToVisit::none;
if (Token::Match(rhs, "%str%|%num%|%name%") && !rhs->varId())
return ChildrenToVisit::none;
if (Token::Match(rhs, ":: %name%") && rhs->hasKnownIntValue())
return ChildrenToVisit::none;
if (rhs->isCast())
return ChildrenToVisit::op2;
trivial = false;
return ChildrenToVisit::done;
});
if (trivial)
continue;
}
const Token* rhs = tok->astOperand2();
// Do not warn about assignment with 0 / NULL
if ((rhs && MathLib::isNullValue(rhs->str())) || isNullOperand(rhs))
continue;
if (tok->astOperand1()->variable() && tok->astOperand1()->variable()->isReference())
// todo: check references
continue;
if (tok->astOperand1()->variable() && tok->astOperand1()->variable()->isStatic())
// todo: check static variables
continue;
bool inconclusive = false;
if (tok->isCpp() && tok->astOperand1()->valueType()) {
// If there is a custom assignment operator => this is inconclusive
if (tok->astOperand1()->valueType()->typeScope) {
const std::string op = "operator" + tok->str();
const std::list<Function>& fList = tok->astOperand1()->valueType()->typeScope->functionList;
inconclusive = std::any_of(fList.cbegin(), fList.cend(), [&](const Function& f) {
return f.name() == op;
});
}
// assigning a smart pointer has side effects
if (tok->astOperand1()->valueType()->type == ValueType::SMART_POINTER)
break;
}
if (inconclusive && !mSettings->certainty.isEnabled(Certainty::inconclusive))
continue;
FwdAnalysis fwdAnalysis(*mSettings);
if (fwdAnalysis.hasOperand(tok->astOperand2(), tok->astOperand1()))
continue;
// Is there a redundant assignment?
const Token *start;
if (tok->isAssignmentOp())
start = tok->astOperand2();
else
start = tok->findExpressionStartEndTokens().second->next();
const Token * tokenToCheck = tok->astOperand1();
// Check if we are working with union
for (const Token* tempToken = tokenToCheck; Token::simpleMatch(tempToken, ".");) {
tempToken = tempToken->astOperand1();
if (tempToken && tempToken->variable() && tempToken->variable()->type() && tempToken->variable()->type()->isUnionType())
tokenToCheck = tempToken;
}
if (start->hasKnownSymbolicValue(tokenToCheck) && Token::simpleMatch(start->astParent(), "=") && !diag(tok)) {
const ValueFlow::Value* val = start->getKnownValue(ValueFlow::Value::ValueType::SYMBOLIC);
if (val->intvalue == 0) // no offset
redundantAssignmentSameValueError(tokenToCheck, val, tok->astOperand1()->expressionString());
}
// Get next assignment..
const Token *nextAssign = fwdAnalysis.reassign(tokenToCheck, start, scope->bodyEnd);
// extra check for union
if (nextAssign && tokenToCheck != tok->astOperand1())
nextAssign = fwdAnalysis.reassign(tok->astOperand1(), start, scope->bodyEnd);
if (!nextAssign)
continue;
// there is redundant assignment. Is there a case between the assignments?
bool hasCase = false;
for (const Token *tok2 = tok; tok2 != nextAssign; tok2 = tok2->next()) {
if (tok2->str() == "break" || tok2->str() == "return")
break;
if (tok2->str() == "case") {
hasCase = true;
break;
}
}
// warn
if (hasCase)
redundantAssignmentInSwitchError(tok, nextAssign, tok->astOperand1()->expressionString());
else if (isInitialization)
redundantInitializationError(tok, nextAssign, tok->astOperand1()->expressionString(), inconclusive);
else {
diag(nextAssign);
redundantAssignmentError(tok, nextAssign, tok->astOperand1()->expressionString(), inconclusive);
}
}
}
}
}
void CheckOther::redundantCopyError(const Token *tok1, const Token* tok2, const std::string& var)
{
const std::list<const Token *> callstack = { tok1, tok2 };
reportError(callstack, Severity::performance, "redundantCopy",
"$symbol:" + var + "\n"
"Buffer '$symbol' is being written before its old content has been used.", CWE563, Certainty::normal);
}
void CheckOther::redundantAssignmentError(const Token *tok1, const Token* tok2, const std::string& var, bool inconclusive)
{
ErrorPath errorPath = { ErrorPathItem(tok1, var + " is assigned"), ErrorPathItem(tok2, var + " is overwritten") };
if (inconclusive)
reportError(std::move(errorPath), Severity::style, "redundantAssignment",
"$symbol:" + var + "\n"
"Variable '$symbol' is reassigned a value before the old one has been used if variable is no semaphore variable.\n"
"Variable '$symbol' is reassigned a value before the old one has been used. Make sure that this variable is not used like a semaphore in a threading environment before simplifying this code.", CWE563, Certainty::inconclusive);
else
reportError(std::move(errorPath), Severity::style, "redundantAssignment",
"$symbol:" + var + "\n"
"Variable '$symbol' is reassigned a value before the old one has been used.", CWE563, Certainty::normal);
}
void CheckOther::redundantInitializationError(const Token *tok1, const Token* tok2, const std::string& var, bool inconclusive)
{
ErrorPath errorPath = { ErrorPathItem(tok1, var + " is initialized"), ErrorPathItem(tok2, var + " is overwritten") };
reportError(std::move(errorPath), Severity::style, "redundantInitialization",
"$symbol:" + var + "\nRedundant initialization for '$symbol'. The initialized value is overwritten before it is read.",
CWE563,
inconclusive ? Certainty::inconclusive : Certainty::normal);
}
void CheckOther::redundantAssignmentInSwitchError(const Token *tok1, const Token* tok2, const std::string &var)
{
ErrorPath errorPath = { ErrorPathItem(tok1, "$symbol is assigned"), ErrorPathItem(tok2, "$symbol is overwritten") };
reportError(std::move(errorPath), Severity::style, "redundantAssignInSwitch",
"$symbol:" + var + "\n"
"Variable '$symbol' is reassigned a value before the old one has been used. 'break;' missing?", CWE563, Certainty::normal);
}
void CheckOther::redundantAssignmentSameValueError(const Token *tok, const ValueFlow::Value* val, const std::string &var)
{
auto errorPath = val->errorPath;
errorPath.emplace_back(tok, "");
reportError(std::move(errorPath), Severity::style, "redundantAssignment",
"$symbol:" + var + "\n"
"Variable '$symbol' is assigned an expression that holds the same value.", CWE563, Certainty::normal);
}
//---------------------------------------------------------------------------
// switch (x)
// {
// case 2:
// y = a; // <- this assignment is redundant
// case 3:
// y = b; // <- case 2 falls through and sets y twice
// }
//---------------------------------------------------------------------------
static inline bool isFunctionOrBreakPattern(const Token *tok)
{
return Token::Match(tok, "%name% (") || Token::Match(tok, "break|continue|return|exit|goto|throw");
}
void CheckOther::redundantBitwiseOperationInSwitchError()
{
if (!mSettings->severity.isEnabled(Severity::warning))
return;
logChecker("CheckOther::redundantBitwiseOperationInSwitch"); // warning
const SymbolDatabase *symbolDatabase = mTokenizer->getSymbolDatabase();
// Find the beginning of a switch. E.g.:
// switch (var) { ...
for (const Scope &switchScope : symbolDatabase->scopeList) {
if (switchScope.type != ScopeType::eSwitch || !switchScope.bodyStart)
continue;
// Check the contents of the switch statement
std::map<int, const Token*> varsWithBitsSet;
std::map<int, std::string> bitOperations;
for (const Token *tok2 = switchScope.bodyStart->next(); tok2 != switchScope.bodyEnd; 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) {
varsWithBitsSet.erase(tok3->varId());
bitOperations.erase(tok3->varId());
} else if (isFunctionOrBreakPattern(tok3)) {
varsWithBitsSet.clear();
bitOperations.clear();
}
}
tok2 = endOfConditional;
}
}
// 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% ;")) {
varsWithBitsSet.erase(tok2->varId());
bitOperations.erase(tok2->varId());
}
// Bitwise operation. Report an error if it's performed twice before a break. E.g.:
// case 3: b |= 1; // <== redundant
// case 4: b |= 1;
else if (Token::Match(tok2->previous(), ";|{|}|: %var% %assign% %num% ;") &&
(tok2->strAt(1) == "|=" || tok2->strAt(1) == "&=") &&
Token::Match(tok2->next()->astOperand2(), "%num%")) {
std::string bitOp = tok2->strAt(1)[0] + tok2->strAt(2);
const auto i2 = utils::as_const(varsWithBitsSet).find(tok2->varId());
// This variable has not had a bit operation performed on it yet, so just make a note of it
if (i2 == varsWithBitsSet.end()) {
varsWithBitsSet[tok2->varId()] = tok2;
bitOperations[tok2->varId()] = std::move(bitOp);
}
// The same bit operation has been performed on the same variable twice, so report an error
else if (bitOperations[tok2->varId()] == bitOp)
redundantBitwiseOperationInSwitchError(i2->second, i2->second->str());
// A different bit operation was performed on the variable, so clear it
else {
varsWithBitsSet.erase(tok2->varId());
bitOperations.erase(tok2->varId());
}
}
// Bitwise operation. Report an error if it's performed twice before a break. E.g.:
// case 3: b = b | 1; // <== redundant
// case 4: b = b | 1;
else if (Token::Match(tok2->previous(), ";|{|}|: %var% = %name% %or%|& %num% ;") &&
tok2->varId() == tok2->tokAt(2)->varId()) {
std::string bitOp = tok2->strAt(3) + tok2->strAt(4);
const auto i2 = utils::as_const(varsWithBitsSet).find(tok2->varId());
// This variable has not had a bit operation performed on it yet, so just make a note of it
if (i2 == varsWithBitsSet.end()) {
varsWithBitsSet[tok2->varId()] = tok2;
bitOperations[tok2->varId()] = std::move(bitOp);
}
// The same bit operation has been performed on the same variable twice, so report an error
else if (bitOperations[tok2->varId()] == bitOp)
redundantBitwiseOperationInSwitchError(i2->second, i2->second->str());
// A different bit operation was performed on the variable, so clear it
else {
varsWithBitsSet.erase(tok2->varId());
bitOperations.erase(tok2->varId());
}
}
// 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 && tok2->strAt(1) != "|" && tok2->strAt(1) != "&") {
varsWithBitsSet.erase(tok2->varId());
bitOperations.erase(tok2->varId());
}
// Reset our record of assignments if there is a break or function call. E.g.:
// case 3: b = 1; break;
if (isFunctionOrBreakPattern(tok2)) {
varsWithBitsSet.clear();
bitOperations.clear();
}
}
}
}
void CheckOther::redundantBitwiseOperationInSwitchError(const Token *tok, const std::string &varname)
{
reportError(tok, Severity::style,
"redundantBitwiseOperationInSwitch",
"$symbol:" + varname + "\n"
"Redundant bitwise operation on '$symbol' in 'switch' statement. 'break;' missing?");
}
//---------------------------------------------------------------------------
// Check for statements like case A||B: in switch()
//---------------------------------------------------------------------------
void CheckOther::checkSuspiciousCaseInSwitch()
{
if (!mSettings->certainty.isEnabled(Certainty::inconclusive) || !mSettings->severity.isEnabled(Severity::warning))
return;
logChecker("CheckOther::checkSuspiciousCaseInSwitch"); // warning,inconclusive
const SymbolDatabase *symbolDatabase = mTokenizer->getSymbolDatabase();
for (const Scope & scope : symbolDatabase->scopeList) {
if (scope.type != ScopeType::eSwitch)
continue;
for (const Token* tok = scope.bodyStart->next(); tok != scope.bodyEnd; tok = tok->next()) {
if (tok->str() == "case") {
const Token* finding = nullptr;
for (const Token* tok2 = tok->next(); tok2; tok2 = tok2->next()) {
if (tok2->str() == ":")
break;
if (Token::Match(tok2, "[;}{]"))
break;
if (tok2->str() == "?")
finding = nullptr;
else if (Token::Match(tok2, "&&|%oror%"))
finding = tok2;
}
if (finding)
suspiciousCaseInSwitchError(finding, finding->str());
}
}
}
}
void CheckOther::suspiciousCaseInSwitchError(const Token* tok, const std::string& operatorString)
{
reportError(tok, Severity::warning, "suspiciousCase",
"Found suspicious case label in switch(). Operator '" + operatorString + "' probably doesn't work as intended.\n"
"Using an operator like '" + operatorString + "' in a case label is suspicious. Did you intend to use a bitwise operator, multiple case labels or if/else instead?", CWE398, Certainty::inconclusive);
}
static bool isNestedInSwitch(const Scope* scope)
{
while (scope) {
if (scope->type == ScopeType::eSwitch)
return true;
if (scope->type == ScopeType::eUnconditional) {
scope = scope->nestedIn;
continue;
}
break;
}
return false;
}
static bool isVardeclInSwitch(const Token* tok)
{
if (!tok)
return false;
if (!isNestedInSwitch(tok->scope()))
return false;
if (const Token* end = Token::findsimplematch(tok, ";")) {
for (const Token* tok2 = tok; tok2 != end; tok2 = tok2->next()) {
if (tok2->isKeyword() && tok2->str() == "case")
return false;
if (tok2->variable() && tok2->variable()->nameToken() == tok2) {
end = tok2->scope()->bodyEnd;
for (const Token* tok3 = tok2; tok3 != end; tok3 = tok3->next()) {
if (tok3->isKeyword())
return tok3->str() == "case";
}
return false;