forked from danmar/cppcheck
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcheckuninitvar.cpp
1815 lines (1608 loc) · 74.1 KB
/
checkuninitvar.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-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 "checkuninitvar.h"
#include "astutils.h"
#include "ctu.h"
#include "errorlogger.h"
#include "library.h"
#include "mathlib.h"
#include "settings.h"
#include "symboldatabase.h"
#include "token.h"
#include "tokenize.h"
#include "tokenlist.h"
#include "utils.h"
#include "vfvalue.h"
#include "checknullpointer.h" // CheckNullPointer::isPointerDeref
#include <algorithm>
#include <cassert>
#include <functional>
#include <initializer_list>
#include <list>
#include <map>
#include <unordered_set>
#include <vector>
//---------------------------------------------------------------------------
// CWE ids used:
static const CWE CWE_USE_OF_UNINITIALIZED_VARIABLE(457U);
// Register this check class (by creating a static instance of it)
namespace {
CheckUninitVar instance;
}
//---------------------------------------------------------------------------
// get ast parent, skip possible address-of and casts
static const Token *getAstParentSkipPossibleCastAndAddressOf(const Token *vartok, bool *unknown)
{
if (unknown)
*unknown = false;
if (!vartok)
return nullptr;
const Token *parent = vartok->astParent();
while (Token::Match(parent, ".|::"))
parent = parent->astParent();
if (!parent)
return nullptr;
if (parent->isUnaryOp("&"))
parent = parent->astParent();
else if (parent->str() == "&" && vartok == parent->astOperand2() && Token::Match(parent->astOperand1()->previous(), "( %type% )")) {
parent = parent->astParent();
if (unknown)
*unknown = true;
}
while (parent && parent->isCast())
parent = parent->astParent();
return parent;
}
static std::map<nonneg int, VariableValue> getVariableValues(const Token* tok) {
std::map<nonneg int, VariableValue> ret;
if (!tok || !tok->scope()->isExecutable())
return ret;
while (tok && tok->str() != "{") {
if (tok->str() == "}") {
if (tok->link()->isBinaryOp())
tok = tok->link()->previous();
else
break;
}
if (Token::Match(tok, "%var% =|{") && tok->next()->isBinaryOp() && tok->varId() && ret.count(tok->varId()) == 0) {
const Token* rhs = tok->next()->astOperand2();
if (rhs && rhs->hasKnownIntValue())
ret[tok->varId()] = VariableValue(rhs->getKnownIntValue());
}
tok = tok->previous();
}
return ret;
}
bool CheckUninitVar::diag(const Token* tok)
{
if (!tok)
return true;
while (Token::Match(tok->astParent(), "*|&|."))
tok = tok->astParent();
return !mUninitDiags.insert(tok).second;
}
void CheckUninitVar::check()
{
logChecker("CheckUninitVar::check");
const SymbolDatabase *symbolDatabase = mTokenizer->getSymbolDatabase();
std::set<std::string> arrayTypeDefs;
for (const Token *tok = mTokenizer->tokens(); tok; tok = tok->next()) {
if (Token::Match(tok, "%name% [") && tok->variable() && Token::Match(tok->variable()->typeStartToken(), "%type% %var% ;"))
arrayTypeDefs.insert(tok->variable()->typeStartToken()->str());
}
// check every executable scope
for (const Scope &scope : symbolDatabase->scopeList) {
if (scope.isExecutable()) {
checkScope(&scope, arrayTypeDefs);
}
}
}
void CheckUninitVar::checkScope(const Scope* scope, const std::set<std::string> &arrayTypeDefs)
{
for (const Variable &var : scope->varlist) {
if ((mTokenizer->isCPP() && var.type() && !var.isPointer() && var.type()->needInitialization != Type::NeedInitialization::True) ||
var.isStatic() || var.isExtern() || var.isReference())
continue;
// don't warn for try/catch exception variable
if (var.isThrow())
continue;
if (Token::Match(var.nameToken()->next(), "[({:]"))
continue;
if (Token::Match(var.nameToken(), "%name% =")) { // Variable is initialized, but Rhs might be not
checkRhs(var.nameToken(), var, NO_ALLOC, 0U, emptyString);
continue;
}
if (Token::Match(var.nameToken(), "%name% ) (") && Token::simpleMatch(var.nameToken()->linkAt(2), ") =")) { // Function pointer is initialized, but Rhs might be not
checkRhs(var.nameToken()->linkAt(2)->next(), var, NO_ALLOC, 0U, emptyString);
continue;
}
if (var.isArray() || var.isPointerToArray()) {
const Token *tok = var.nameToken()->next();
if (var.isPointerToArray())
tok = tok->next();
while (Token::simpleMatch(tok->link(), "] ["))
tok = tok->link()->next();
if (Token::Match(tok->link(), "] =|{|("))
continue;
}
bool stdtype = var.typeStartToken()->isC() && arrayTypeDefs.find(var.typeStartToken()->str()) == arrayTypeDefs.end();
const Token* tok = var.typeStartToken();
for (; tok != var.nameToken() && tok->str() != "<"; tok = tok->next()) {
if (tok->isStandardType() || tok->isEnumType())
stdtype = true;
}
if (var.isArray() && !stdtype) { // std::array
if (!(var.isStlType() && Token::simpleMatch(var.typeStartToken(), "std :: array") && var.valueType() &&
var.valueType()->containerTypeToken && var.valueType()->containerTypeToken->isStandardType()))
continue;
}
while (tok && tok->str() != ";")
tok = tok->next();
if (!tok)
continue;
if (tok->astParent() && Token::simpleMatch(tok->astParent()->previous(), "for (") && Token::simpleMatch(tok->astParent()->link()->next(), "{") &&
checkLoopBody(tok->astParent()->link()->next(), var, var.isArray() ? ARRAY : NO_ALLOC, emptyString, true))
continue;
if (var.isArray()) {
bool init = false;
for (const Token *parent = var.nameToken(); parent; parent = parent->astParent()) {
if (parent->str() == "=") {
init = true;
break;
}
}
if (!init) {
Alloc alloc = ARRAY;
std::map<nonneg int, VariableValue> variableValue = getVariableValues(var.typeStartToken());
checkScopeForVariable(tok, var, nullptr, nullptr, &alloc, emptyString, variableValue);
}
continue;
}
if (stdtype || var.isPointer()) {
Alloc alloc = NO_ALLOC;
std::map<nonneg int, VariableValue> variableValue = getVariableValues(var.typeStartToken());
checkScopeForVariable(tok, var, nullptr, nullptr, &alloc, emptyString, variableValue);
}
if (var.type())
checkStruct(tok, var);
}
if (scope->function) {
for (const Variable &arg : scope->function->argumentList) {
if (arg.declarationId() && Token::Match(arg.typeStartToken(), "%type% * %name% [,)]")) {
// Treat the pointer as initialized until it is assigned by malloc
for (const Token *tok = scope->bodyStart; tok != scope->bodyEnd; tok = tok->next()) {
if (!Token::Match(tok, "[;{}] %varid% =", arg.declarationId()))
continue;
const Token *allocFuncCallToken = findAllocFuncCallToken(tok->tokAt(2)->astOperand2(), mSettings->library);
if (!allocFuncCallToken)
continue;
const Library::AllocFunc *allocFunc = mSettings->library.getAllocFuncInfo(allocFuncCallToken);
if (!allocFunc || allocFunc->initData)
continue;
if (arg.typeStartToken()->strAt(-1) == "struct" || (arg.type() && arg.type()->isStructType()))
checkStruct(tok, arg);
else if (arg.typeStartToken()->isStandardType() || arg.typeStartToken()->isEnumType()) {
Alloc alloc = NO_ALLOC;
std::map<nonneg int, VariableValue> variableValue;
checkScopeForVariable(tok->next(), arg, nullptr, nullptr, &alloc, emptyString, variableValue);
}
}
}
}
}
}
void CheckUninitVar::checkStruct(const Token *tok, const Variable &structvar)
{
const Token *typeToken = structvar.typeStartToken();
while (Token::Match(typeToken, "%name% ::"))
typeToken = typeToken->tokAt(2);
const SymbolDatabase * symbolDatabase = mTokenizer->getSymbolDatabase();
for (const Scope *scope2 : symbolDatabase->classAndStructScopes) {
if (scope2->className == typeToken->str() && scope2->numConstructors == 0U) {
for (const Variable &var : scope2->varlist) {
if (var.isStatic() || var.hasDefault() || var.isArray() ||
(!mTokenizer->isC() && var.isClass() && (!var.type() || var.type()->needInitialization != Type::NeedInitialization::True)))
continue;
// is the variable declared in a inner union?
bool innerunion = false;
for (const Scope *innerScope : scope2->nestedList) {
if (innerScope->type == ScopeType::eUnion) {
if (var.typeStartToken()->linenr() >= innerScope->bodyStart->linenr() &&
var.typeStartToken()->linenr() <= innerScope->bodyEnd->linenr()) {
innerunion = true;
break;
}
}
}
if (!innerunion) {
Alloc alloc = NO_ALLOC;
const Token *tok2 = tok;
if (tok->str() == "}")
tok2 = tok2->next();
std::map<nonneg int, VariableValue> variableValue = getVariableValues(structvar.typeStartToken());
checkScopeForVariable(tok2, structvar, nullptr, nullptr, &alloc, var.name(), variableValue);
}
}
}
}
}
static VariableValue operator!(VariableValue v)
{
v.notEqual = !v.notEqual;
return v;
}
static bool operator==(const VariableValue & v, MathLib::bigint i)
{
return v.notEqual ? (i != v.value) : (i == v.value);
}
static bool operator!=(const VariableValue & v, MathLib::bigint i)
{
return v.notEqual ? (i == v.value) : (i != v.value);
}
static void conditionAlwaysTrueOrFalse(const Token *tok, const std::map<nonneg int, VariableValue> &variableValue, bool *alwaysTrue, bool *alwaysFalse)
{
if (!tok)
return;
if (const ValueFlow::Value* v = tok->getKnownValue(ValueFlow::Value::ValueType::INT)) {
if (v->intvalue == 0)
*alwaysFalse = true;
else
*alwaysTrue = true;
return;
}
if (tok->isName() || tok->str() == ".") {
while (tok && tok->str() == ".")
tok = tok->astOperand2();
const auto it = utils::as_const(variableValue).find(tok ? tok->varId() : ~0U);
if (it != variableValue.end()) {
*alwaysTrue = (it->second != 0LL);
*alwaysFalse = (it->second == 0LL);
}
}
else if (tok->isComparisonOp()) {
if (variableValue.empty()) {
return;
}
const Token *vartok, *numtok;
if (tok->astOperand2() && tok->astOperand2()->isNumber()) {
vartok = tok->astOperand1();
numtok = tok->astOperand2();
} else if (tok->astOperand1() && tok->astOperand1()->isNumber()) {
vartok = tok->astOperand2();
numtok = tok->astOperand1();
} else {
return;
}
while (vartok && vartok->str() == ".")
vartok = vartok->astOperand2();
const auto it = utils::as_const(variableValue).find(vartok ? vartok->varId() : ~0U);
if (it == variableValue.end())
return;
if (tok->str() == "==")
*alwaysTrue = (it->second == MathLib::toBigNumber(numtok));
else if (tok->str() == "!=")
*alwaysTrue = (it->second != MathLib::toBigNumber(numtok));
else
return;
*alwaysFalse = !(*alwaysTrue);
}
else if (tok->str() == "!") {
bool t=false,f=false;
conditionAlwaysTrueOrFalse(tok->astOperand1(), variableValue, &t, &f);
if (t || f) {
*alwaysTrue = !t;
*alwaysFalse = !f;
}
}
else if (tok->str() == "||") {
bool t1=false, f1=false;
conditionAlwaysTrueOrFalse(tok->astOperand1(), variableValue, &t1, &f1);
bool t2=false, f2=false;
if (!t1)
conditionAlwaysTrueOrFalse(tok->astOperand2(), variableValue, &t2, &f2);
*alwaysTrue = (t1 || t2);
*alwaysFalse = (f1 && f2);
}
else if (tok->str() == "&&") {
bool t1=false, f1=false;
conditionAlwaysTrueOrFalse(tok->astOperand1(), variableValue, &t1, &f1);
bool t2=false, f2=false;
if (!f1)
conditionAlwaysTrueOrFalse(tok->astOperand2(), variableValue, &t2, &f2);
*alwaysTrue = (t1 && t2);
*alwaysFalse = (f1 || f2);
}
}
static bool isVariableUsed(const Token *tok, const Variable& var)
{
if (!tok)
return false;
if (tok->str() == "&" && !tok->astOperand2())
return false;
if (tok->isConstOp())
return isVariableUsed(tok->astOperand1(),var) || isVariableUsed(tok->astOperand2(),var);
if (tok->varId() != var.declarationId())
return false;
if (!var.isArray())
return true;
const Token *parent = tok->astParent();
while (Token::Match(parent, "[?:]"))
parent = parent->astParent();
// no dereference, then array is not "used"
if (!Token::Match(parent, "*|["))
return false;
const Token *parent2 = parent->astParent();
// TODO: handle function calls. There is a TODO assertion in TestUninitVar::uninitvar_arrays
return !parent2 || parent2->isConstOp() || (parent2->str() == "=" && parent2->astOperand2() == parent);
}
bool CheckUninitVar::checkScopeForVariable(const Token *tok, const Variable& var, bool * const possibleInit, bool * const noreturn, Alloc* const alloc, const std::string &membervar, std::map<nonneg int, VariableValue>& variableValue)
{
const bool suppressErrors(possibleInit && *possibleInit); // Assume that this is a variable declaration, rather than a fundef
const bool printDebug = mSettings->debugwarnings;
if (possibleInit)
*possibleInit = false;
int number_of_if = 0;
if (var.declarationId() == 0U)
return true;
for (; tok; tok = tok->next()) {
// End of scope..
if (tok->str() == "}") {
if (number_of_if && possibleInit)
*possibleInit = true;
// might be a noreturn function..
if (mTokenizer->isScopeNoReturn(tok)) {
if (noreturn)
*noreturn = true;
return false;
}
break;
}
// Unconditional inner scope, try, lambda, init list
if (tok->str() == "{" && Token::Match(tok->previous(), ",|;|{|}|]|try")) {
bool possibleInitInner = false;
if (checkScopeForVariable(tok->next(), var, &possibleInitInner, noreturn, alloc, membervar, variableValue))
return true;
tok = tok->link();
if (possibleInitInner) {
number_of_if = 1;
if (possibleInit)
*possibleInit = true;
}
continue;
}
// track values of other variables..
if (Token::Match(tok->previous(), "[;{}.] %var% =")) {
if (tok->next()->astOperand2() && tok->next()->astOperand2()->hasKnownIntValue())
variableValue[tok->varId()] = VariableValue(tok->next()->astOperand2()->getKnownIntValue());
else if (Token::Match(tok->previous(), "[;{}] %var% = - %name% ;"))
variableValue[tok->varId()] = !VariableValue(0);
else
variableValue.erase(tok->varId());
}
// Inner scope..
else if (Token::simpleMatch(tok, "if (")) {
bool alwaysTrue = false;
bool alwaysFalse = false;
// Is variable assigned in condition?
if (!membervar.empty()) {
for (const Token *cond = tok->linkAt(1); cond != tok; cond = cond->previous()) {
if (cond->varId() == var.declarationId() && isMemberVariableAssignment(cond, membervar))
return true;
}
}
conditionAlwaysTrueOrFalse(tok->next()->astOperand2(), variableValue, &alwaysTrue, &alwaysFalse);
// initialization / usage in condition..
if (!alwaysTrue && checkIfForWhileHead(tok->next(), var, suppressErrors, (number_of_if == 0), *alloc, membervar))
return true;
// checking if a not-zero variable is zero => bail out
nonneg int condVarId = 0;
VariableValue condVarValue(0);
const Token *condVarTok = nullptr;
if (alwaysFalse)
;
else if (astIsVariableComparison(tok->next()->astOperand2(), "!=", "0", &condVarTok)) {
const auto it = utils::as_const(variableValue).find(condVarTok->varId());
if (it != variableValue.cend() && it->second != 0)
return true; // this scope is not fully analysed => return true
condVarId = condVarTok->varId();
condVarValue = !VariableValue(0);
} else if (Token::Match(tok->next()->astOperand2(), "==|!=")) {
const Token *condition = tok->next()->astOperand2();
const Token *lhs = condition->astOperand1();
const Token *rhs = condition->astOperand2();
const Token *vartok = (lhs && lhs->hasKnownIntValue()) ? rhs : lhs;
const Token *numtok = (lhs == vartok) ? rhs : lhs;
while (Token::simpleMatch(vartok, "."))
vartok = vartok->astOperand2();
if (vartok && vartok->varId() && numtok && numtok->hasKnownIntValue()) {
const auto it = utils::as_const(variableValue).find(vartok->varId());
if (it != variableValue.cend() && it->second != numtok->getKnownIntValue())
return true; // this scope is not fully analysed => return true
condVarId = vartok->varId();
condVarValue = VariableValue(numtok->getKnownIntValue());
if (condition->str() == "!=")
condVarValue = !condVarValue;
}
}
// goto the {
tok = tok->linkAt(1)->next();
if (!tok)
break;
if (tok->str() == "{") {
bool possibleInitIf((!alwaysTrue && number_of_if > 0) || suppressErrors);
bool noreturnIf = false;
std::map<nonneg int, VariableValue> varValueIf(variableValue);
const bool initif = !alwaysFalse && checkScopeForVariable(tok->next(), var, &possibleInitIf, &noreturnIf, alloc, membervar, varValueIf);
// bail out for such code:
// if (a) x=0; // conditional initialization
// if (b) return; // cppcheck doesn't know if b can be false when a is false.
// x++; // it's possible x is always initialized
if (!alwaysTrue && noreturnIf && number_of_if > 0) {
if (printDebug) {
std::string condition;
for (const Token *tok2 = tok->linkAt(-1); tok2 != tok; tok2 = tok2->next()) {
condition += tok2->str();
if (tok2->isName() && tok2->next()->isName())
condition += ' ';
}
reportError(tok, Severity::debug, "bailoutUninitVar", "bailout uninitialized variable checking for '" + var.name() + "'. can't determine if this condition can be false when previous condition is false: " + condition);
}
return true;
}
if (alwaysTrue && (initif || noreturnIf))
return true;
if (!alwaysFalse && !initif && !noreturnIf)
variableValue = varValueIf;
if (initif && condVarId > 0)
variableValue[condVarId] = !condVarValue;
// goto the }
tok = tok->link();
if (!Token::simpleMatch(tok, "} else {")) {
if (initif || possibleInitIf) {
++number_of_if;
if (number_of_if >= 2)
return true;
}
} else {
// goto the {
tok = tok->tokAt(2);
bool possibleInitElse((!alwaysFalse && number_of_if > 0) || suppressErrors);
bool noreturnElse = false;
std::map<nonneg int, VariableValue> varValueElse(variableValue);
const bool initelse = !alwaysTrue && checkScopeForVariable(tok->next(), var, &possibleInitElse, &noreturnElse, alloc, membervar, varValueElse);
if (!alwaysTrue && !initelse && !noreturnElse)
variableValue = varValueElse;
if (initelse && condVarId > 0 && !noreturnIf && !noreturnElse)
variableValue[condVarId] = condVarValue;
// goto the }
tok = tok->link();
if ((alwaysFalse || initif || noreturnIf) &&
(alwaysTrue || initelse || noreturnElse))
return true;
if (initif || initelse || possibleInitElse)
++number_of_if;
if (!initif && !noreturnIf)
variableValue.insert(varValueIf.cbegin(), varValueIf.cend());
if (!initelse && !noreturnElse)
variableValue.insert(varValueElse.cbegin(), varValueElse.cend());
}
}
}
// = { .. }
else if (Token::simpleMatch(tok, "= {") || (Token::Match(tok, "%name% {") && tok->variable() && tok == tok->variable()->nameToken())) {
// end token
const Token *end = tok->linkAt(1);
// If address of variable is taken in the block then bail out
if (var.isPointer() || var.isArray()) {
if (Token::findmatch(tok->tokAt(2), "%varid%", end, var.declarationId()))
return true;
} else if (Token::findmatch(tok->tokAt(2), "& %varid%", end, var.declarationId())) {
return true;
}
const Token *errorToken = nullptr;
visitAstNodes(tok->next(),
[&](const Token *child) {
if (child->isUnaryOp("&"))
return ChildrenToVisit::none;
if (child->str() == "," || child->str() == "{" || child->isConstOp())
return ChildrenToVisit::op1_and_op2;
if (child->str() == "." && Token::Match(child->astOperand1(), "%varid%", var.declarationId()) && child->astOperand2() && child->astOperand2()->str() == membervar) {
errorToken = child;
return ChildrenToVisit::done;
}
return ChildrenToVisit::none;
});
if (errorToken) {
uninitStructMemberError(errorToken->astOperand2(), errorToken->astOperand1()->str() + "." + membervar);
return true;
}
// Skip block
tok = end;
continue;
}
// skip sizeof / offsetof
if (isUnevaluated(tok))
tok = tok->linkAt(1);
// for/while..
else if (Token::Match(tok, "for|while (") || Token::simpleMatch(tok, "do {")) {
const bool forwhile = Token::Match(tok, "for|while (");
// is variable initialized in for-head?
if (forwhile && checkIfForWhileHead(tok->next(), var, tok->str() == "for", false, *alloc, membervar))
return true;
// goto the {
const Token *tok2 = forwhile ? tok->linkAt(1)->next() : tok->next();
if (tok2 && tok2->str() == "{") {
const bool init = checkLoopBody(tok2, var, *alloc, membervar, (number_of_if > 0) || suppressErrors);
// variable is initialized in the loop..
if (init)
return true;
// is variable used in for-head?
bool initcond = false;
if (!suppressErrors) {
const Token *startCond = forwhile ? tok->next() : tok->linkAt(1)->tokAt(2);
initcond = checkIfForWhileHead(startCond, var, false, (number_of_if == 0), *alloc, membervar);
}
// goto "}"
tok = tok2->link();
// do-while => goto ")"
if (!forwhile) {
// Assert that the tokens are '} while ('
if (!Token::simpleMatch(tok, "} while (")) {
if (printDebug)
reportError(tok,Severity::debug,"","assertion failed '} while ('");
break;
}
// Goto ')'
tok = tok->linkAt(2);
if (!tok)
// bailout : invalid code / bad tokenizer
break;
if (initcond)
// variable is initialized in while-condition
return true;
}
}
}
// Unknown or unhandled inner scope
else if (Token::simpleMatch(tok, ") {") || (Token::Match(tok, "%name% {") && tok->str() != "try" && !(tok->variable() && tok == tok->variable()->nameToken()))) {
if (tok->str() == "struct" || tok->str() == "union") {
tok = tok->linkAt(1);
continue;
}
return true;
}
// bailout if there is ({
if (Token::simpleMatch(tok, "( {")) {
return true;
}
// bailout if there is assembler code or setjmp
if (Token::Match(tok, "asm|setjmp (")) {
return true;
}
// bailout if there is a goto label
if (Token::Match(tok, "[;{}] %name% :")) {
return true;
}
// bailout if there is a pointer to member
if (Token::Match(tok, "%varid% . *", var.declarationId())) {
return true;
}
if (tok->str() == "?") {
if (!tok->astOperand2())
return true;
const bool used1 = isVariableUsed(tok->astOperand2()->astOperand1(), var);
const bool used0 = isVariableUsed(tok->astOperand2()->astOperand2(), var);
const bool err = (number_of_if == 0) ? (used1 || used0) : (used1 && used0);
if (err)
uninitvarError(tok, var.nameToken()->str(), *alloc);
// Todo: skip expression if there is no error
return true;
}
if (Token::Match(tok, "return|break|continue|throw|goto")) {
if (noreturn)
*noreturn = true;
tok = tok->next();
while (tok && tok->str() != ";") {
// variable is seen..
if (tok->varId() == var.declarationId()) {
if (!membervar.empty()) {
if (!suppressErrors && Token::Match(tok, "%name% . %name%") && tok->strAt(2) == membervar && Token::Match(tok->next()->astParent(), "%cop%|return|throw|?"))
uninitStructMemberError(tok, tok->str() + "." + membervar);
else if (tok->isCpp() && !suppressErrors && Token::Match(tok, "%name%") && Token::Match(tok->astParent(), "return|throw|?")) {
if (std::any_of(tok->values().cbegin(), tok->values().cend(), [](const ValueFlow::Value& v) {
return v.isUninitValue() && !v.isInconclusive();
}))
uninitStructMemberError(tok, tok->str() + "." + membervar);
}
}
// Use variable
else if (!suppressErrors && isVariableUsage(tok, var.isPointer(), *alloc))
uninitvarError(tok, tok->str(), *alloc);
return true;
}
if (isUnevaluated(tok))
tok = tok->linkAt(1);
else if (tok->str() == "?") {
if (!tok->astOperand2())
return true;
const bool used1 = isVariableUsed(tok->astOperand2()->astOperand1(), var);
const bool used0 = isVariableUsed(tok->astOperand2()->astOperand2(), var);
const bool err = (number_of_if == 0) ? (used1 || used0) : (used1 && used0);
if (err)
uninitvarError(tok, var.nameToken()->str(), *alloc);
return true;
}
tok = tok->next();
}
return (noreturn == nullptr);
}
// variable is seen..
if (tok->varId() == var.declarationId()) {
// calling function that returns uninit data through pointer..
if (var.isPointer() && Token::simpleMatch(tok->next(), "=")) {
const Token *rhs = tok->next()->astOperand2();
while (rhs && rhs->isCast())
rhs = rhs->astOperand2() ? rhs->astOperand2() : rhs->astOperand1();
if (rhs && Token::Match(rhs->previous(), "%name% (")) {
const Library::AllocFunc *allocFunc = mSettings->library.getAllocFuncInfo(rhs->astOperand1());
if (allocFunc && !allocFunc->initData) {
*alloc = NO_CTOR_CALL;
continue;
}
}
}
if (mTokenizer->isCPP() && var.isPointer() && (var.typeStartToken()->isStandardType() || var.typeStartToken()->isEnumType() || (var.type() && var.type()->needInitialization == Type::NeedInitialization::True)) && Token::simpleMatch(tok->next(), "= new")) {
*alloc = CTOR_CALL;
// type has constructor(s)
if (var.typeScope() && var.typeScope()->numConstructors > 0)
return true;
// standard or enum type: check if new initializes the allocated memory
if (var.typeStartToken()->isStandardType() || var.typeStartToken()->isEnumType()) {
// scalar new with initialization
if (Token::Match(tok->next(), "= new %type% ("))
return true;
// array new
if (Token::Match(tok->next(), "= new %type% [") && Token::simpleMatch(tok->linkAt(4), "] ("))
return true;
}
continue;
}
if (!membervar.empty()) {
if (isMemberVariableAssignment(tok, membervar)) {
checkRhs(tok, var, *alloc, number_of_if, membervar);
return true;
}
if (isMemberVariableUsage(tok, var.isPointer(), *alloc, membervar)) {
uninitStructMemberError(tok, tok->str() + "." + membervar);
return true;
}
if (Token::Match(tok->previous(), "[(,] %name% [,)]"))
return true;
if (Token::Match(tok->previous(), "= %var% . %var% ;") && membervar == tok->strAt(2))
return true;
} else {
// Use variable
if (!suppressErrors && isVariableUsage(tok, var.isPointer(), *alloc)) {
uninitvarError(tok, tok->str(), *alloc);
return true;
}
const Token *parent = tok;
while (parent->astParent() && ((astIsLHS(parent) && parent->astParent()->str() == "[") || parent->astParent()->isUnaryOp("*"))) {
parent = parent->astParent();
if (parent->str() == "[") {
if (const Token *errorToken = checkExpr(parent->astOperand2(), var, *alloc, number_of_if==0)) {
if (!suppressErrors)
uninitvarError(errorToken, errorToken->expressionString(), *alloc);
return true;
}
}
}
if (Token::simpleMatch(parent->astParent(), "=") && astIsLHS(parent)) {
const Token *eq = parent->astParent();
if (const Token *errorToken = checkExpr(eq->astOperand2(), var, *alloc, number_of_if==0)) {
if (!suppressErrors)
uninitvarError(errorToken, errorToken->expressionString(), *alloc);
return true;
}
}
// assume that variable is assigned
return true;
}
}
}
return false;
}
const Token* CheckUninitVar::checkExpr(const Token* tok, const Variable& var, const Alloc alloc, bool known, bool* bailout) const
{
if (!tok)
return nullptr;
if (isUnevaluated(tok->previous()))
return nullptr;
if (tok->astOperand1()) {
bool bailout1 = false;
const Token *errorToken = checkExpr(tok->astOperand1(), var, alloc, known, &bailout1);
if (bailout && bailout1)
*bailout = true;
if (errorToken)
return errorToken;
if ((bailout1 || !known) && Token::Match(tok, "%oror%|&&|?"))
return nullptr;
}
if (tok->astOperand2())
return checkExpr(tok->astOperand2(), var, alloc, known, bailout);
if (tok->varId() == var.declarationId()) {
const Token *errorToken = isVariableUsage(tok, var.isPointer(), alloc);
if (errorToken)
return errorToken;
if (bailout)
*bailout = true;
}
return nullptr;
}
bool CheckUninitVar::checkIfForWhileHead(const Token *startparentheses, const Variable& var, bool suppressErrors, bool isuninit, Alloc alloc, const std::string &membervar)
{
const Token * const endpar = startparentheses->link();
if (Token::Match(startparentheses, "( ! %name% %oror%") && startparentheses->tokAt(2)->getValue(0))
suppressErrors = true;
for (const Token *tok = startparentheses->next(); tok && tok != endpar; tok = tok->next()) {
if (tok->varId() == var.declarationId()) {
if (Token::Match(tok, "%name% . %name%")) {
if (membervar.empty())
return true;
if (tok->strAt(2) == membervar) {
if (isMemberVariableAssignment(tok, membervar))
return true;
if (!suppressErrors && isMemberVariableUsage(tok, var.isPointer(), alloc, membervar))
uninitStructMemberError(tok, tok->str() + "." + membervar);
}
continue;
}
if (const Token *errorToken = isVariableUsage(tok, var.isPointer(), alloc)) {
if (suppressErrors)
continue;
uninitvarError(errorToken, errorToken->expressionString(), alloc);
}
return true;
}
// skip sizeof / offsetof
if (isUnevaluated(tok))
tok = tok->linkAt(1);
if ((!isuninit || !membervar.empty()) && tok->str() == "&&")
suppressErrors = true;
}
return false;
}
/** recursively check loop, return error token */
const Token* CheckUninitVar::checkLoopBodyRecursive(const Token *start, const Variable& var, const Alloc alloc, const std::string &membervar, bool &bailout, bool &alwaysReturns) const
{
assert(start->str() == "{");
const Token *errorToken = nullptr;
const Token *const end = start->link();
for (const Token *tok = start->next(); tok != end; tok = tok->next()) {
// skip sizeof / offsetof
if (isUnevaluated(tok)) {
tok = tok->linkAt(1);
continue;
}
if (Token::Match(tok, "asm ( %str% ) ;")) {
bailout = true;
return nullptr;
}
// for loop; skip third expression until loop body has been analyzed..
if (tok->str() == ";" && Token::simpleMatch(tok->astParent(), ";") && Token::simpleMatch(tok->astParent()->astParent(), "(")) {
const Token *top = tok->astParent()->astParent();
if (!Token::simpleMatch(top->previous(), "for (") || !Token::simpleMatch(top->link(), ") {"))
continue;
const Token *bodyStart = top->link()->next();
const Token *errorToken1 = checkLoopBodyRecursive(bodyStart, var, alloc, membervar, bailout, alwaysReturns);
if (!errorToken)
errorToken = errorToken1;
bailout |= alwaysReturns;
if (bailout)
return nullptr;
}
// for loop; skip loop body if there is third expression
if (Token::simpleMatch(tok, ") {") &&
Token::simpleMatch(tok->link()->previous(), "for (") &&
Token::simpleMatch(tok->link()->astOperand2(), ";") &&
Token::simpleMatch(tok->link()->astOperand2()->astOperand2(), ";")) {
tok = tok->linkAt(1);
}
if (tok->str() == "{") {
// switch => bailout
if (tok->scope() && tok->scope()->type == ScopeType::eSwitch) {
bailout = true;
return nullptr;
}
bool alwaysReturnsUnused;
const Token *errorToken1 = checkLoopBodyRecursive(tok, var, alloc, membervar, bailout, alwaysReturnsUnused);
tok = tok->link();
if (Token::simpleMatch(tok, "} else {")) {
const Token *elseBody = tok->tokAt(2);
const Token *errorToken2 = checkLoopBodyRecursive(elseBody, var, alloc, membervar, bailout, alwaysReturnsUnused);
tok = elseBody->link();
if (errorToken1 && errorToken2)
return errorToken1;
if (errorToken2)
errorToken = errorToken2;
}
if (bailout)
return nullptr;
if (!errorToken)
errorToken = errorToken1;
}
if (Token::simpleMatch(tok, "return")) {
bool returnWithoutVar = true;
while (tok && !Token::simpleMatch(tok, ";")) {
if (tok->isVariable() && tok->variable() == &var) {
returnWithoutVar = false;
break;
}
tok = tok->next();
}
if (returnWithoutVar) {
alwaysReturns = true;
return nullptr;
}
}
if (!tok)
break;
if (tok->varId() != var.declarationId())
continue;