forked from danmar/cppcheck
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcheckclass.cpp
2661 lines (2313 loc) · 114 KB
/
checkclass.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-2019 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 "checkclass.h"
#include "astutils.h"
#include "errorlogger.h"
#include "library.h"
#include "settings.h"
#include "standards.h"
#include "symboldatabase.h"
#include "token.h"
#include "tokenize.h"
#include "utils.h"
#include <algorithm>
#include <cstdlib>
#include <stack>
#include <utility>
//---------------------------------------------------------------------------
// Register CheckClass..
namespace {
CheckClass instance;
}
static const CWE CWE398(398U); // Indicator of Poor Code Quality
static const CWE CWE404(404U); // Improper Resource Shutdown or Release
static const CWE CWE665(665U); // Improper Initialization
static const CWE CWE758(758U); // Reliance on Undefined, Unspecified, or Implementation-Defined Behavior
static const CWE CWE762(762U); // Mismatched Memory Management Routines
static const char * getFunctionTypeName(Function::Type type)
{
switch (type) {
case Function::eConstructor:
return "constructor";
case Function::eCopyConstructor:
return "copy constructor";
case Function::eMoveConstructor:
return "move constructor";
case Function::eDestructor:
return "destructor";
case Function::eFunction:
return "function";
case Function::eOperatorEqual:
return "operator=";
}
return "";
}
static bool isVariableCopyNeeded(const Variable &var)
{
return var.isPointer() || (var.type() && var.type()->needInitialization == Type::True) || (var.valueType()->type >= ValueType::Type::CHAR);
}
//---------------------------------------------------------------------------
CheckClass::CheckClass(const Tokenizer *tokenizer, const Settings *settings, ErrorLogger *errorLogger)
: Check(myName(), tokenizer, settings, errorLogger),
mSymbolDatabase(tokenizer?tokenizer->getSymbolDatabase():nullptr)
{
}
//---------------------------------------------------------------------------
// ClassCheck: Check that all class constructors are ok.
//---------------------------------------------------------------------------
void CheckClass::constructors()
{
const bool printStyle = mSettings->isEnabled(Settings::STYLE);
const bool printWarnings = mSettings->isEnabled(Settings::WARNING);
if (!printStyle && !printWarnings)
return;
const bool printInconclusive = mSettings->inconclusive;
for (const Scope * scope : mSymbolDatabase->classAndStructScopes) {
bool usedInUnion = false;
for (const Scope &unionScope : mSymbolDatabase->scopeList) {
if (unionScope.type != Scope::eUnion)
continue;
for (const Variable &var : unionScope.varlist) {
if (var.type() && var.type()->classScope == scope) {
usedInUnion = true;
break;
}
}
}
// There are no constructors.
if (scope->numConstructors == 0 && printStyle && !usedInUnion) {
// If there is a private variable, there should be a constructor..
for (const Variable &var : scope->varlist) {
const Token *initTok = var.nameToken();
while (Token::simpleMatch(initTok->next(), "["))
initTok = initTok->linkAt(1);
if (var.isPrivate() && !var.isStatic() && !Token::Match(var.nameToken(), "%varid% ; %varid% =", var.declarationId()) &&
!Token::Match(initTok, "%var%|] {|=") &&
(!var.isClass() || (var.type() && var.type()->needInitialization == Type::True))) {
noConstructorError(scope->classDef, scope->className, scope->classDef->str() == "struct");
break;
}
}
}
if (!printWarnings)
continue;
// #3196 => bailout if there are nested unions
// TODO: handle union variables better
{
bool bailout = false;
for (const Scope * const nestedScope : scope->nestedList) {
if (nestedScope->type == Scope::eUnion) {
bailout = true;
break;
}
}
if (bailout)
continue;
}
std::vector<Usage> usage(scope->varlist.size());
for (const Function &func : scope->functionList) {
if (!func.hasBody() || !(func.isConstructor() || func.type == Function::eOperatorEqual))
continue;
// Bail: If initializer list is not recognized as a variable or type then skip since parsing is incomplete
if (func.type == Function::eConstructor) {
const Token *initList = func.constructorMemberInitialization();
if (Token::Match(initList, ": %name% (") && initList->next()->tokType() == Token::eName)
break;
}
// Mark all variables not used
clearAllVar(usage);
std::list<const Function *> callstack;
initializeVarList(func, callstack, scope, usage);
// Check if any variables are uninitialized
int count = -1;
for (const Variable &var : scope->varlist) {
++count;
// check for C++11 initializer
if (var.hasDefault()) {
usage[count].init = true;
continue;
}
if (usage[count].assign || usage[count].init || var.isStatic())
continue;
if (var.valueType()->pointer == 0 && var.type() && var.type()->needInitialization == Type::False && var.type()->derivedFrom.empty())
continue;
if (var.isConst() && func.isOperator()) // We can't set const members in assignment operator
continue;
// Check if this is a class constructor
if (!var.isPointer() && !var.isPointerArray() && var.isClass() && func.type == Function::eConstructor) {
// Unknown type so assume it is initialized
if (!var.type())
continue;
// Known type that doesn't need initialization or
// known type that has member variables of an unknown type
else if (var.type()->needInitialization != Type::True)
continue;
}
// Check if type can't be copied
if (!var.isPointer() && !var.isPointerArray() && var.typeScope()) {
if (func.type == Function::eMoveConstructor) {
if (canNotMove(var.typeScope()))
continue;
} else {
if (canNotCopy(var.typeScope()))
continue;
}
}
bool inconclusive = false;
// Don't warn about unknown types in copy constructors since we
// don't know if they can be copied or not..
if ((func.type == Function::eCopyConstructor || func.type == Function::eMoveConstructor || func.type == Function::eOperatorEqual) && !isVariableCopyNeeded(var))
inconclusive = true;
if (!printInconclusive && inconclusive)
continue;
// It's non-static and it's not initialized => error
if (func.type == Function::eOperatorEqual) {
const Token *operStart = func.arg;
bool classNameUsed = false;
for (const Token *operTok = operStart; operTok != operStart->link(); operTok = operTok->next()) {
if (operTok->str() == scope->className) {
classNameUsed = true;
break;
}
}
if (classNameUsed)
operatorEqVarError(func.token, scope->className, var.name(), inconclusive);
} else if (func.access != Private || mSettings->standards.cpp >= Standards::CPP11) {
// If constructor is not in scope then we maybe using a oonstructor from a different template specialization
if (!precedes(scope->bodyStart, func.tokenDef))
continue;
const Scope *varType = var.typeScope();
if (!varType || varType->type != Scope::eUnion) {
if (func.type == Function::eConstructor &&
func.nestedIn && (func.nestedIn->numConstructors - func.nestedIn->numCopyOrMoveConstructors) > 1 &&
func.argCount() == 0 && func.functionScope &&
func.arg && func.arg->link()->next() == func.functionScope->bodyStart &&
func.functionScope->bodyStart->link() == func.functionScope->bodyStart->next()) {
// don't warn about user defined default constructor when there are other constructors
if (printInconclusive)
uninitVarError(func.token, func.access == Private, scope->className, var.name(), true);
} else
uninitVarError(func.token, func.access == Private, scope->className, var.name(), inconclusive);
}
}
}
}
}
}
void CheckClass::checkExplicitConstructors()
{
if (!mSettings->isEnabled(Settings::STYLE))
return;
for (const Scope * scope : mSymbolDatabase->classAndStructScopes) {
// Do not perform check, if the class/struct has not any constructors
if (scope->numConstructors == 0)
continue;
// Is class abstract? Maybe this test is over-simplification, but it will suffice for simple cases,
// and it will avoid false positives.
bool isAbstractClass = false;
for (const Function &func : scope->functionList) {
if (func.isPure()) {
isAbstractClass = true;
break;
}
}
// Abstract classes can't be instantiated. But if there is C++11
// "misuse" by derived classes then these constructors must be explicit.
if (isAbstractClass && mSettings->standards.cpp != Standards::CPP11)
continue;
for (const Function &func : scope->functionList) {
// We are looking for constructors, which are meeting following criteria:
// 1) Constructor is declared with a single parameter
// 2) Constructor is not declared as explicit
// 3) It is not a copy/move constructor of non-abstract class
// 4) Constructor is not marked as delete (programmer can mark the default constructor as deleted, which is ok)
if (!func.isConstructor() || func.isDelete() || (!func.hasBody() && func.access == Private))
continue;
if (!func.isExplicit() &&
func.minArgCount() == 1 &&
func.type != Function::eCopyConstructor &&
func.type != Function::eMoveConstructor) {
noExplicitConstructorError(func.tokenDef, scope->className, scope->type == Scope::eStruct);
}
}
}
}
static bool isNonCopyable(const Scope *scope, bool *unknown)
{
bool u = false;
// check if there is base class that is not copyable
for (const Type::BaseInfo &baseInfo : scope->definedType->derivedFrom) {
if (!baseInfo.type || !baseInfo.type->classScope) {
u = true;
continue;
}
if (isNonCopyable(baseInfo.type->classScope, &u))
return true;
for (const Function &func : baseInfo.type->classScope->functionList) {
if (func.type != Function::eCopyConstructor)
continue;
if (func.access == Private || func.isDelete())
return true;
}
}
*unknown = u;
return false;
}
void CheckClass::copyconstructors()
{
if (!mSettings->isEnabled(Settings::WARNING))
return;
for (const Scope * scope : mSymbolDatabase->classAndStructScopes) {
std::map<unsigned int, const Token*> allocatedVars;
for (const Function &func : scope->functionList) {
if (func.type != Function::eConstructor || !func.functionScope)
continue;
const Token* tok = func.token->linkAt(1);
for (const Token* const end = func.functionScope->bodyStart; tok != end; tok = tok->next()) {
if (Token::Match(tok, "%var% ( new") ||
(Token::Match(tok, "%var% ( %name% (") && mSettings->library.alloc(tok->tokAt(2)))) {
const Variable* var = tok->variable();
if (var && var->isPointer() && var->scope() == scope)
allocatedVars[tok->varId()] = tok;
}
}
for (const Token* const end = func.functionScope->bodyEnd; tok != end; tok = tok->next()) {
if (Token::Match(tok, "%var% = new") ||
(Token::Match(tok, "%var% = %name% (") && mSettings->library.alloc(tok->tokAt(2)))) {
const Variable* var = tok->variable();
if (var && var->isPointer() && var->scope() == scope && !var->isStatic())
allocatedVars[tok->varId()] = tok;
}
}
}
if (!allocatedVars.empty()) {
const Function *funcCopyCtor = nullptr;
const Function *funcOperatorEq = nullptr;
const Function *funcDestructor = nullptr;
for (const Function &func : scope->functionList) {
if (func.type == Function::eCopyConstructor)
funcCopyCtor = &func;
else if (func.type == Function::eOperatorEqual)
funcOperatorEq = &func;
else if (func.type == Function::eDestructor)
funcDestructor = &func;
}
if (!funcCopyCtor || funcCopyCtor->isDefault()) {
bool unknown = false;
if (!isNonCopyable(scope, &unknown) && !unknown)
noCopyConstructorError(scope, funcCopyCtor, allocatedVars.begin()->second, unknown);
}
if (!funcOperatorEq || funcOperatorEq->isDefault()) {
bool unknown = false;
if (!isNonCopyable(scope, &unknown) && !unknown)
noOperatorEqError(scope, funcOperatorEq, allocatedVars.begin()->second, unknown);
}
if (!funcDestructor || funcDestructor->isDefault()) {
const Token * mustDealloc = nullptr;
for (std::map<unsigned int, const Token*>::const_iterator it = allocatedVars.begin(); it != allocatedVars.end(); ++it) {
if (!Token::Match(it->second, "%var% [(=] new %type%")) {
mustDealloc = it->second;
break;
}
if (it->second->valueType() && it->second->valueType()->isIntegral()) {
mustDealloc = it->second;
break;
}
const Variable *var = it->second->variable();
if (var && var->typeScope() && var->typeScope()->functionList.empty() && var->type()->derivedFrom.empty())
mustDealloc = it->second;
}
if (mustDealloc)
noDestructorError(scope, funcDestructor, mustDealloc);
}
}
std::set<const Token*> copiedVars;
const Token* copyCtor = nullptr;
for (const Function &func : scope->functionList) {
if (func.type != Function::eCopyConstructor)
continue;
copyCtor = func.tokenDef;
if (!func.functionScope) {
allocatedVars.clear();
break;
}
const Token* tok = func.tokenDef->linkAt(1)->next();
if (tok->str()==":") {
tok=tok->next();
while (Token::Match(tok, "%name% (")) {
if (allocatedVars.find(tok->varId()) != allocatedVars.end()) {
if (tok->varId() && Token::Match(tok->tokAt(2), "%name% . %name% )"))
copiedVars.insert(tok);
else if (!Token::Match(tok->tokAt(2), "%any% )"))
allocatedVars.erase(tok->varId()); // Assume memory is allocated
}
tok = tok->linkAt(1)->tokAt(2);
}
}
for (tok = func.functionScope->bodyStart; tok != func.functionScope->bodyEnd; tok = tok->next()) {
if (Token::Match(tok, "%var% = new|malloc|g_malloc|g_try_malloc|realloc|g_realloc|g_try_realloc")) {
allocatedVars.erase(tok->varId());
} else if (Token::Match(tok, "%var% = %name% . %name% ;") && allocatedVars.find(tok->varId()) != allocatedVars.end()) {
copiedVars.insert(tok);
}
}
break;
}
if (copyCtor && !copiedVars.empty()) {
for (const Token *cv : copiedVars)
copyConstructorShallowCopyError(cv, cv->str());
// throw error if count mismatch
/* FIXME: This doesn't work. See #4154
for (std::map<unsigned int, const Token*>::const_iterator i = allocatedVars.begin(); i != allocatedVars.end(); ++i) {
copyConstructorMallocError(copyCtor, i->second, i->second->str());
}
*/
}
}
}
/* This doesn't work. See #4154
void CheckClass::copyConstructorMallocError(const Token *cctor, const Token *alloc, const std::string& varname)
{
std::list<const Token*> callstack;
callstack.push_back(cctor);
callstack.push_back(alloc);
reportError(callstack, Severity::warning, "copyCtorNoAllocation", "Copy constructor does not allocate memory for member '" + varname + "' although memory has been allocated in other constructors.");
}
*/
void CheckClass::copyConstructorShallowCopyError(const Token *tok, const std::string& varname)
{
reportError(tok, Severity::warning, "copyCtorPointerCopying",
"$symbol:" + varname + "\nValue of pointer '$symbol', which points to allocated memory, is copied in copy constructor instead of allocating new memory.", CWE398, false);
}
static std::string noMemberErrorMessage(const Scope *scope, const char function[], bool isdefault)
{
const std::string &classname = scope ? scope->className : "class";
const std::string type = (scope && scope->type == Scope::eStruct) ? "Struct" : "Class";
const bool isDestructor = (function[0] == 'd');
std::string errmsg = "$symbol:" + classname + '\n';
if (isdefault) {
errmsg += type + " '$symbol' has dynamic memory/resource allocation(s). The " + function + " is explicitly defaulted but the default " + function + " does not work well.";
if (isDestructor)
errmsg += " It is recommended to define the " + std::string(function) + '.';
else
errmsg += " It is recommended to define or delete the " + std::string(function) + '.';
} else {
errmsg += type + " '$symbol' does not have a " + function + " which is recommended since it has dynamic memory/resource allocation(s).";
}
return errmsg;
}
void CheckClass::noCopyConstructorError(const Scope *scope, bool isdefault, const Token *alloc, bool inconclusive)
{
reportError(alloc, Severity::warning, "noCopyConstructor", noMemberErrorMessage(scope, "copy constructor", isdefault), CWE398, inconclusive);
}
void CheckClass::noOperatorEqError(const Scope *scope, bool isdefault, const Token *alloc, bool inconclusive)
{
reportError(alloc, Severity::warning, "noOperatorEq", noMemberErrorMessage(scope, "operator=", isdefault), CWE398, inconclusive);
}
void CheckClass::noDestructorError(const Scope *scope, bool isdefault, const Token *alloc)
{
reportError(alloc, Severity::warning, "noDestructor", noMemberErrorMessage(scope, "destructor", isdefault), CWE398, false);
}
bool CheckClass::canNotCopy(const Scope *scope)
{
bool constructor = false;
bool publicAssign = false;
bool publicCopy = false;
for (const Function &func : scope->functionList) {
if (func.isConstructor())
constructor = true;
if (func.access != Public)
continue;
if (func.type == Function::eCopyConstructor) {
publicCopy = true;
break;
} else if (func.type == Function::eOperatorEqual) {
publicAssign = true;
break;
}
}
return constructor && !(publicAssign || publicCopy);
}
bool CheckClass::canNotMove(const Scope *scope)
{
bool constructor = false;
bool publicAssign = false;
bool publicCopy = false;
bool publicMove = false;
for (const Function &func : scope->functionList) {
if (func.isConstructor())
constructor = true;
if (func.access != Public)
continue;
if (func.type == Function::eCopyConstructor) {
publicCopy = true;
break;
} else if (func.type == Function::eMoveConstructor) {
publicMove = true;
break;
} else if (func.type == Function::eOperatorEqual) {
publicAssign = true;
break;
}
}
return constructor && !(publicAssign || publicCopy || publicMove);
}
void CheckClass::assignVar(unsigned int varid, const Scope *scope, std::vector<Usage> &usage)
{
unsigned int count = 0;
for (std::list<Variable>::const_iterator var = scope->varlist.begin(); var != scope->varlist.end(); ++var, ++count) {
if (var->declarationId() == varid) {
usage[count].assign = true;
return;
}
}
}
void CheckClass::initVar(unsigned int varid, const Scope *scope, std::vector<Usage> &usage)
{
unsigned int count = 0;
for (std::list<Variable>::const_iterator var = scope->varlist.begin(); var != scope->varlist.end(); ++var, ++count) {
if (var->declarationId() == varid) {
usage[count].init = true;
return;
}
}
}
void CheckClass::assignAllVar(std::vector<Usage> &usage)
{
for (std::size_t i = 0; i < usage.size(); ++i)
usage[i].assign = true;
}
void CheckClass::clearAllVar(std::vector<Usage> &usage)
{
for (std::size_t i = 0; i < usage.size(); ++i) {
usage[i].assign = false;
usage[i].init = false;
}
}
bool CheckClass::isBaseClassFunc(const Token *tok, const Scope *scope)
{
// Iterate through each base class...
for (std::size_t i = 0; i < scope->definedType->derivedFrom.size(); ++i) {
const Type *derivedFrom = scope->definedType->derivedFrom[i].type;
// Check if base class exists in database
if (derivedFrom && derivedFrom->classScope) {
const std::list<Function>& functionList = derivedFrom->classScope->functionList;
for (const Function &func : functionList) {
if (func.tokenDef->str() == tok->str())
return true;
}
}
// Base class not found so assume it is in it.
else
return true;
}
return false;
}
void CheckClass::initializeVarList(const Function &func, std::list<const Function *> &callstack, const Scope *scope, std::vector<Usage> &usage)
{
if (!func.functionScope)
throw InternalError(nullptr, "Internal Error: Invalid syntax"); // #5702
bool initList = func.isConstructor();
const Token *ftok = func.arg->link()->next();
int level = 0;
for (; ftok && ftok != func.functionScope->bodyEnd; ftok = ftok->next()) {
// Class constructor.. initializing variables like this
// clKalle::clKalle() : var(value) { }
if (initList) {
if (level == 0 && Token::Match(ftok, "%name% {|(") && Token::Match(ftok->linkAt(1), "}|) ,|{")) {
if (ftok->str() != func.name()) {
initVar(ftok->varId(), scope, usage);
} else { // c++11 delegate constructor
const Function *member = ftok->function();
// member function not found => assume it initializes all members
if (!member) {
assignAllVar(usage);
return;
}
// recursive call
// assume that all variables are initialized
if (std::find(callstack.begin(), callstack.end(), member) != callstack.end()) {
/** @todo false negative: just bail */
assignAllVar(usage);
return;
}
// member function has implementation
if (member->hasBody()) {
// initialize variable use list using member function
callstack.push_back(member);
initializeVarList(*member, callstack, scope, usage);
callstack.pop_back();
}
// there is a called member function, but it has no implementation, so we assume it initializes everything
else {
assignAllVar(usage);
}
}
} else if (level != 0 && Token::Match(ftok, "%name% =")) // assignment in the initializer: var(value = x)
assignVar(ftok->varId(), scope, usage);
// Level handling
if (ftok->link() && Token::Match(ftok, "(|<"))
level++;
else if (ftok->str() == "{") {
if (level != 0 ||
(Token::Match(ftok->previous(), "%name%|>") && Token::Match(ftok->link(), "} ,|{")))
level++;
else
initList = false;
} else if (ftok->link() && Token::Match(ftok, ")|>|}"))
level--;
}
if (initList)
continue;
// Variable getting value from stream?
if (Token::Match(ftok, ">>|& %name%") && isLikelyStreamRead(true, ftok)) {
assignVar(ftok->next()->varId(), scope, usage);
}
// If assignment comes after an && or || this is really inconclusive because of short circuiting
if (Token::Match(ftok, "%oror%|&&"))
continue;
if (Token::simpleMatch(ftok, "( !"))
ftok = ftok->next();
// Using the operator= function to initialize all variables..
if (Token::Match(ftok->next(), "return| (| * this )| =")) {
assignAllVar(usage);
break;
}
// Using swap to assign all variables..
if (func.type == Function::eOperatorEqual && Token::Match(ftok, "[;{}] %name% (") && Token::Match(ftok->linkAt(2), ") . %name% ( *| this ) ;")) {
assignAllVar(usage);
break;
}
// Calling member variable function?
if (Token::Match(ftok->next(), "%var% . %name% (")) {
for (const Variable &var : scope->varlist) {
if (var.declarationId() == ftok->next()->varId()) {
/** @todo false negative: we assume function changes variable state */
assignVar(ftok->next()->varId(), scope, usage);
break;
}
}
ftok = ftok->tokAt(2);
}
if (!Token::Match(ftok->next(), "::| %name%") &&
!Token::Match(ftok->next(), "*| this . %name%") &&
!Token::Match(ftok->next(), "* %name% =") &&
!Token::Match(ftok->next(), "( * this ) . %name%"))
continue;
// Goto the first token in this statement..
ftok = ftok->next();
// skip "return"
if (ftok->str() == "return")
ftok = ftok->next();
// Skip "( * this )"
if (Token::simpleMatch(ftok, "( * this ) .")) {
ftok = ftok->tokAt(5);
}
// Skip "this->"
if (Token::simpleMatch(ftok, "this ."))
ftok = ftok->tokAt(2);
// Skip "classname :: "
if (Token::Match(ftok, ":: %name%"))
ftok = ftok->next();
while (Token::Match(ftok, "%name% ::"))
ftok = ftok->tokAt(2);
// Clearing all variables..
if (Token::Match(ftok, "::| memset ( this ,")) {
assignAllVar(usage);
return;
}
// Ticket #7068
else if (Token::Match(ftok, "::| memset ( &| this . %name%")) {
if (ftok->str() == "::")
ftok = ftok->next();
int offsetToMember = 4;
if (ftok->strAt(2) == "&")
++offsetToMember;
assignVar(ftok->tokAt(offsetToMember)->varId(), scope, usage);
ftok = ftok->linkAt(1);
continue;
}
// Clearing array..
else if (Token::Match(ftok, "::| memset ( %name% ,")) {
if (ftok->str() == "::")
ftok = ftok->next();
assignVar(ftok->tokAt(2)->varId(), scope, usage);
ftok = ftok->linkAt(1);
continue;
}
// Calling member function?
else if (Token::simpleMatch(ftok, "operator= (") &&
ftok->previous()->str() != "::") {
if (ftok->function() && ftok->function()->nestedIn == scope) {
const Function *member = ftok->function();
// recursive call
// assume that all variables are initialized
if (std::find(callstack.begin(), callstack.end(), member) != callstack.end()) {
/** @todo false negative: just bail */
assignAllVar(usage);
return;
}
// member function has implementation
if (member->hasBody()) {
// initialize variable use list using member function
callstack.push_back(member);
initializeVarList(*member, callstack, scope, usage);
callstack.pop_back();
}
// there is a called member function, but it has no implementation, so we assume it initializes everything
else {
assignAllVar(usage);
}
}
// using default operator =, assume everything initialized
else {
assignAllVar(usage);
}
} else if (Token::Match(ftok, "::| %name% (") && !Token::Match(ftok, "if|while|for")) {
if (ftok->str() == "::")
ftok = ftok->next();
// Passing "this" => assume that everything is initialized
for (const Token *tok2 = ftok->next()->link(); tok2 && tok2 != ftok; tok2 = tok2->previous()) {
if (tok2->str() == "this") {
assignAllVar(usage);
return;
}
}
// check if member function
if (ftok->function() && ftok->function()->nestedIn == scope &&
!ftok->function()->isConstructor()) {
const Function *member = ftok->function();
// recursive call
// assume that all variables are initialized
if (std::find(callstack.begin(), callstack.end(), member) != callstack.end()) {
assignAllVar(usage);
return;
}
// member function has implementation
if (member->hasBody()) {
// initialize variable use list using member function
callstack.push_back(member);
initializeVarList(*member, callstack, scope, usage);
callstack.pop_back();
// Assume that variables that are passed to it are initialized..
for (const Token *tok2 = ftok; tok2; tok2 = tok2->next()) {
if (Token::Match(tok2, "[;{}]"))
break;
if (Token::Match(tok2, "[(,] &| %name% [,)]")) {
tok2 = tok2->next();
if (tok2->str() == "&")
tok2 = tok2->next();
assignVar(tok2->varId(), scope, usage);
}
}
}
// there is a called member function, but it has no implementation, so we assume it initializes everything
else {
assignAllVar(usage);
}
}
// not member function
else {
// could be a base class virtual function, so we assume it initializes everything
if (!func.isConstructor() && isBaseClassFunc(ftok, scope)) {
/** @todo False Negative: we should look at the base class functions to see if they
* call any derived class virtual functions that change the derived class state
*/
assignAllVar(usage);
}
// has friends, so we assume it initializes everything
if (!scope->definedType->friendList.empty())
assignAllVar(usage);
// the function is external and it's neither friend nor inherited virtual function.
// assume all variables that are passed to it are initialized..
else {
for (const Token *tok = ftok->tokAt(2); tok && tok != ftok->next()->link(); tok = tok->next()) {
if (tok->isName()) {
assignVar(tok->varId(), scope, usage);
}
}
}
}
}
// Assignment of member variable?
else if (Token::Match(ftok, "%name% =")) {
assignVar(ftok->varId(), scope, usage);
bool bailout = ftok->variable() && ftok->variable()->isReference();
const Token* tok2 = ftok->tokAt(2);
if (tok2->str() == "&") {
tok2 = tok2->next();
bailout = true;
}
if (tok2->variable() && (bailout || tok2->variable()->isArray()) && tok2->strAt(1) != "[")
assignVar(tok2->varId(), scope, usage);
}
// Assignment of array item of member variable?
else if (Token::Match(ftok, "%name% [|.")) {
const Token *tok2 = ftok;
while (tok2) {
if (tok2->strAt(1) == "[")
tok2 = tok2->next()->link();
else if (Token::Match(tok2->next(), ". %name%"))
tok2 = tok2->tokAt(2);
else
break;
}
if (tok2 && tok2->strAt(1) == "=")
assignVar(ftok->varId(), scope, usage);
}
// Assignment of array item of member variable?
else if (Token::Match(ftok, "* %name% =")) {
assignVar(ftok->next()->varId(), scope, usage);
} else if (Token::Match(ftok, "* this . %name% =")) {
assignVar(ftok->tokAt(3)->varId(), scope, usage);
}
// The functions 'clear' and 'Clear' are supposed to initialize variable.
if (Token::Match(ftok, "%name% . clear|Clear (")) {
assignVar(ftok->varId(), scope, usage);
}
}
}
void CheckClass::noConstructorError(const Token *tok, const std::string &classname, bool isStruct)
{
// For performance reasons the constructor might be intentionally missing. Therefore this is not a "warning"
reportError(tok, Severity::style, "noConstructor",
"$symbol:" + classname + "\n" +
"The " + std::string(isStruct ? "struct" : "class") + " '$symbol' does not have a constructor although it has private member variables.\n"
"The " + std::string(isStruct ? "struct" : "class") + " '$symbol' does not have a constructor "
"although it has private member variables. Member variables of builtin types are left "
"uninitialized when the class is instantiated. That may cause bugs or undefined behavior.", CWE398, false);
}
void CheckClass::noExplicitConstructorError(const Token *tok, const std::string &classname, bool isStruct)
{
const std::string message(std::string(isStruct ? "Struct" : "Class") + " '$symbol' has a constructor with 1 argument that is not explicit.");
const std::string verbose(message + " Such constructors should in general be explicit for type safety reasons. Using the explicit keyword in the constructor means some mistakes when using the class can be avoided.");
reportError(tok, Severity::style, "noExplicitConstructor", "$symbol:" + classname + '\n' + message + '\n' + verbose, CWE398, false);
}
void CheckClass::uninitVarError(const Token *tok, bool isprivate, const std::string &classname, const std::string &varname, bool inconclusive)
{
reportError(tok, Severity::warning, isprivate ? "uninitMemberVarPrivate" : "uninitMemberVar", "$symbol:" + classname + "::" + varname + "\nMember variable '$symbol' is not initialized in the constructor.", CWE398, inconclusive);
}
void CheckClass::operatorEqVarError(const Token *tok, const std::string &classname, const std::string &varname, bool inconclusive)
{
reportError(tok, Severity::warning, "operatorEqVarError", "$symbol:" + classname + "::" + varname + "\nMember variable '$symbol' is not assigned a value in '" + classname + "::operator='.", CWE398, inconclusive);
}
//---------------------------------------------------------------------------
// ClassCheck: Use initialization list instead of assignment
//---------------------------------------------------------------------------
void CheckClass::initializationListUsage()
{
if (!mSettings->isEnabled(Settings::PERFORMANCE))
return;
for (const Scope *scope : mSymbolDatabase->functionScopes) {
// Check every constructor
if (!scope->function || (!scope->function->isConstructor()))
continue;
const Scope* owner = scope->functionOf;
for (const Token* tok = scope->bodyStart; tok != scope->bodyEnd; tok = tok->next()) {
if (Token::Match(tok, "%name% (")) // Assignments might depend on this function call or if/for/while/switch statement from now on.
break;
if (Token::Match(tok, "try|do {"))
break;
if (!Token::Match(tok, "%var% =") || tok->strAt(-1) == "*")
continue;
const Variable* var = tok->variable();
if (!var || var->scope() != owner || var->isStatic())
continue;
if (var->isPointer() || var->isReference() || var->isEnumType() || var->valueType()->type > ValueType::Type::ITERATOR)
continue;
// bailout: multi line lambda in rhs => do not warn
if (findLambdaEndToken(tok->tokAt(2)) && tok->tokAt(2)->findExpressionStartEndTokens().second->linenr() > tok->tokAt(2)->linenr())
continue;
// Access local var member in rhs => do not warn
bool localmember = false;
visitAstNodes(tok->next()->astOperand2(),
[&](const Token *rhs) {
if (rhs->str() == "." && rhs->astOperand1() && rhs->astOperand1()->variable() && rhs->astOperand1()->variable()->isLocal())
localmember = true;
return ChildrenToVisit::op1_and_op2;
});
if (localmember)
continue;
bool allowed = true;
visitAstNodes(tok->next()->astOperand2(),
[&](const Token *tok2) {
const Variable* var2 = tok2->variable();
if (var2) {
if (var2->scope() == owner && tok2->strAt(-1)!=".") { // Is there a dependency between two member variables?
allowed = false;
return ChildrenToVisit::done;
} else if (var2->isArray() && var2->isLocal()) { // Can't initialize with a local array
allowed = false;
return ChildrenToVisit::done;
}
} else if (tok2->str() == "this") { // 'this' instance is not completely constructed in initialization list
allowed = false;
return ChildrenToVisit::done;
} else if (Token::Match(tok2, "%name% (") && tok2->strAt(-1) != "." && isMemberFunc(owner, tok2)) { // Member function called?
allowed = false;
return ChildrenToVisit::done;
}
return ChildrenToVisit::op1_and_op2;
});
if (!allowed)
continue;
suggestInitializationList(tok, tok->str());
}
}