forked from danmar/cppcheck
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcheckmemoryleak.cpp
2762 lines (2299 loc) · 101 KB
/
checkmemoryleak.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-2012 Daniel Marjamäki and Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "checkmemoryleak.h"
#include "symboldatabase.h"
#include "mathlib.h"
#include "tokenize.h"
#include <algorithm>
#include <cstring>
#include <cstdlib>
#include <sstream>
#include <set>
#include <stack>
//---------------------------------------------------------------------------
// Register this check class (by creating a static instance of it)
namespace {
CheckMemoryLeakInFunction instance1;
CheckMemoryLeakInClass instance2;
CheckMemoryLeakStructMember instance3;
CheckMemoryLeakNoVar instance4;
}
/**
* Count function parameters
* \param tok Function name token before the '('
*/
static unsigned int countParameters(const Token *tok)
{
tok = tok->tokAt(2);
if (tok->str() == ")")
return 0;
unsigned int numpar = 1;
while (NULL != (tok = tok->nextArgument()))
numpar++;
return numpar;
}
/** List of functions that can be ignored when searching for memory leaks.
* These functions don't take the address of the given pointer
* This list needs to be alphabetically sorted so we can run bsearch on it.
* This list contains function names with const parameters e.g.: atof(const char *)
* Reference: http://www.aquaphoenix.com/ref/gnu_c_library/libc_492.html#SEC492
*/
static const char * const call_func_white_list[] = {
"_open", "_wopen", "access", "adjtime", "asctime", "asctime_r", "asprintf", "assert"
, "atof", "atoi", "atol", "chdir", "chmod", "chown"
, "clearerr", "creat", "ctime", "ctime_r", "delete", "execl", "execle"
, "execlp", "execv", "execve", "fchmod", "fclose", "fcntl"
, "fdatasync", "feof", "ferror", "fflush", "fgetc", "fgetpos", "fgets"
, "flock", "fmemopen", "fnmatch", "fopen", "fopencookie", "for", "fprintf", "fputc", "fputs", "fread", "free"
, "freopen", "fscanf", "fseek", "fseeko", "fsetpos", "fstat", "fsync", "ftell", "ftello"
, "ftruncate", "fwrite", "getc", "getenv","getgrnam", "gethostbyaddr", "gethostbyname", "getnetbyname"
, "getopt", "getopt_long", "getprotobyname", "getpwnam", "gets", "getservbyname", "getservbyport"
, "glob", "gmtime", "gmtime_r", "if", "index", "inet_addr", "inet_aton", "inet_network", "initgroups", "ioctl"
, "link", "localtime", "localtime_r"
, "lockf", "lseek", "lstat", "mblen", "mbstowcs", "mbtowc", "memchr", "memcmp", "memcpy", "memmove", "memset"
, "mkdir", "mkfifo", "mknod", "mkstemp"
, "obstack_printf", "obstack_vprintf", "open", "opendir", "parse_printf_format", "pathconf"
, "perror", "popen" ,"posix_fadvise", "posix_fallocate", "pread"
, "printf", "psignal", "puts", "pwrite", "qsort", "read", "readahead", "readdir", "readdir_r"
, "readlink", "readv"
, "realloc", "regcomp", "remove", "rename", "return", "rewind", "rewinddir", "rindex"
, "rmdir" ,"scandir", "scanf", "seekdir"
, "setbuf", "setbuffer", "sethostname", "setlinebuf", "setlocale" ,"setvbuf", "sizeof" ,"snprintf", "sprintf", "sscanf"
, "stat", "stpcpy", "strcasecmp", "strcat", "strchr", "strcmp", "strcoll"
, "strcpy", "strcspn", "strdup", "stricmp", "strlen", "strncasecmp", "strncat", "strncmp"
, "strncpy", "strpbrk","strrchr", "strspn", "strstr", "strtod", "strtok", "strtol", "strtoul", "strxfrm", "switch"
, "symlink", "sync_file_range", "system", "telldir", "tempnam", "time", "typeid", "unlink"
, "utime", "utimes", "vasprintf", "vfprintf", "vfscanf", "vprintf"
, "vscanf", "vsnprintf", "vsprintf", "vsscanf", "while", "wordexp","write", "writev"
};
static int call_func_white_list_compare(const void *a, const void *b)
{
return strcmp((const char *)a, *(const char * const *)b);
}
//---------------------------------------------------------------------------
bool CheckMemoryLeak::isclass(const Tokenizer *_tokenizer, const Token *tok, unsigned int varid) const
{
if (tok->isStandardType())
return false;
const Variable * var = _tokenizer->getSymbolDatabase()->getVariableFromVarId(varid);
// return false if the type is a simple record type without side effects
// a type that has no side effects (no constructors and no members with constructors)
/** @todo false negative: check base class for side effects */
/** @todo false negative: check constructors for side effects */
if (var && var->type() && var->type()->numConstructors == 0 &&
(var->type()->varlist.empty() || var->type()->needInitialization == Scope::True) &&
var->type()->derivedFrom.empty())
return false;
return true;
}
//---------------------------------------------------------------------------
CheckMemoryLeak::AllocType CheckMemoryLeak::getAllocationType(const Token *tok2, unsigned int varid, std::list<const Token *> *callstack) const
{
// What we may have...
// * var = (char *)malloc(10);
// * var = new char[10];
// * var = strdup("hello");
// * var = strndup("hello", 3);
if (tok2 && tok2->str() == "(") {
tok2 = tok2->link();
tok2 = tok2 ? tok2->next() : NULL;
}
if (! tok2)
return No;
if (! tok2->isName())
return No;
// Does tok2 point on "malloc", "strdup" or "kmalloc"..
static const char * const mallocfunc[] = {
"malloc",
"calloc",
"strdup",
"strndup",
"kmalloc",
"kzalloc",
"kcalloc"
};
for (unsigned int i = 0; i < sizeof(mallocfunc)/sizeof(*mallocfunc); i++) {
if (tok2->str() == mallocfunc[i])
return Malloc;
}
// Using realloc..
if (varid && Token::Match(tok2, "realloc ( %any% ,") && tok2->tokAt(2)->varId() != varid)
return Malloc;
// Does tok2 point on "g_malloc", "g_strdup", ..
static const char * const gmallocfunc[] = {
"g_new",
"g_new0",
"g_try_new",
"g_try_new0",
"g_malloc",
"g_malloc0",
"g_try_malloc",
"g_try_malloc0",
"g_strdup",
"g_strndup",
"g_strdup_printf"
};
for (unsigned int i = 0; i < sizeof(gmallocfunc)/sizeof(*gmallocfunc); i++) {
if (tok2->str() == gmallocfunc[i])
return gMalloc;
}
if (Token::Match(tok2, "new struct| %type% [;()]") ||
Token::Match(tok2, "new ( std :: nothrow ) struct| %type% [;()]") ||
Token::Match(tok2, "new ( nothrow ) struct| %type% [;()]"))
return New;
if (Token::Match(tok2, "new struct| %type% [") ||
Token::Match(tok2, "new ( std :: nothrow ) struct| %type% [") ||
Token::Match(tok2, "new ( nothrow ) struct| %type% ["))
return NewArray;
if (Token::Match(tok2, "fopen|tmpfile|g_fopen ("))
return File;
if (standards.posix) {
if (Token::Match(tok2, "open|openat|creat|mkstemp|mkostemp (")) {
// simple sanity check of function parameters..
// TODO: Make such check for all these functions
unsigned int num = countParameters(tok2);
if (tok2->str() == "open" && num != 2 && num != 3)
return No;
// is there a user function with this name?
if (tokenizer && Token::findmatch(tokenizer->tokens(), ("%type% *|&| " + tok2->str()).c_str()))
return No;
return Fd;
}
if (Token::simpleMatch(tok2, "popen ("))
return Pipe;
if (Token::Match(tok2, "opendir|fdopendir ("))
return Dir;
}
// User function
const Token *ftok = tokenizer->getFunctionTokenByName(tok2->str().c_str());
if (ftok == NULL)
return No;
// Prevent recursion
if (callstack && std::find(callstack->begin(), callstack->end(), ftok) != callstack->end())
return No;
std::list<const Token *> cs;
if (!callstack)
callstack = &cs;
callstack->push_back(ftok);
return functionReturnType(ftok, callstack);
}
CheckMemoryLeak::AllocType CheckMemoryLeak::getReallocationType(const Token *tok2, unsigned int varid) const
{
// What we may have...
// * var = (char *)realloc(..;
if (tok2 && tok2->str() == "(") {
tok2 = tok2->link();
tok2 = tok2 ? tok2->next() : NULL;
}
if (! tok2)
return No;
if (varid > 0 && ! Token::Match(tok2, "%var% ( %varid% [,)]", varid))
return No;
if (tok2->str() == "realloc")
return Malloc;
// GTK memory reallocation..
if (Token::Match(tok2, "g_realloc|g_try_realloc|g_renew|g_try_renew"))
return gMalloc;
return No;
}
CheckMemoryLeak::AllocType CheckMemoryLeak::getDeallocationType(const Token *tok, unsigned int varid) const
{
if (Token::Match(tok, "delete %varid% ;", varid))
return New;
if (Token::Match(tok, "delete [ ] %varid% ;", varid))
return NewArray;
if (Token::Match(tok, "delete ( %varid% ) ;", varid))
return New;
if (Token::Match(tok, "delete [ ] ( %varid% ) ;", varid))
return NewArray;
if (tok && tok->str() == "::")
tok = tok->next();
if (Token::Match(tok, "free|kfree ( %varid% ) [;:]", varid) ||
Token::Match(tok, "free|kfree ( %varid% -", varid) ||
Token::Match(tok, "realloc ( %varid% , 0 ) ;", varid))
return Malloc;
if (Token::Match(tok, "g_free ( %varid% ) ;", varid) ||
Token::Match(tok, "g_free ( %varid% -", varid))
return gMalloc;
if (Token::Match(tok, "fclose ( %varid% )", varid) ||
Token::simpleMatch(tok, "fcloseall ( )"))
return File;
if (Token::Match(tok, "close ( %varid% )", varid))
return Fd;
if (Token::Match(tok, "pclose ( %varid% )", varid))
return Pipe;
if (Token::Match(tok, "closedir ( %varid% )", varid))
return Dir;
return No;
}
CheckMemoryLeak::AllocType CheckMemoryLeak::getDeallocationType(const Token *tok, const std::string &varname) const
{
if (Token::Match(tok, std::string("delete " + varname + " [,;]").c_str()))
return New;
if (Token::Match(tok, std::string("delete [ ] " + varname + " [,;]").c_str()))
return NewArray;
if (Token::Match(tok, std::string("delete ( " + varname + " ) [,;]").c_str()))
return New;
if (Token::Match(tok, std::string("delete [ ] ( " + varname + " ) [,;]").c_str()))
return NewArray;
if (Token::simpleMatch(tok, std::string("free ( " + varname + " ) ;").c_str()) ||
Token::simpleMatch(tok, std::string("kfree ( " + varname + " ) ;").c_str()) ||
Token::simpleMatch(tok, std::string("realloc ( " + varname + " , 0 ) ;").c_str()))
return Malloc;
if (Token::simpleMatch(tok, std::string("g_free ( " + varname + " ) ;").c_str()))
return gMalloc;
if (Token::simpleMatch(tok, std::string("fclose ( " + varname + " )").c_str()) ||
Token::simpleMatch(tok, "fcloseall ( )"))
return File;
if (Token::simpleMatch(tok, std::string("close ( " + varname + " )").c_str()))
return Fd;
if (Token::simpleMatch(tok, std::string("pclose ( " + varname + " )").c_str()))
return Pipe;
if (Token::simpleMatch(tok, std::string("closedir ( " + varname + " )").c_str()))
return Dir;
return No;
}
//--------------------------------------------------------------------------
//--------------------------------------------------------------------------
void CheckMemoryLeak::memoryLeak(const Token *tok, const std::string &varname, AllocType alloctype)
{
if (alloctype == CheckMemoryLeak::File ||
alloctype == CheckMemoryLeak::Pipe ||
alloctype == CheckMemoryLeak::Fd ||
alloctype == CheckMemoryLeak::Dir)
resourceLeakError(tok, varname);
else
memleakError(tok, varname);
}
//---------------------------------------------------------------------------
void CheckMemoryLeak::reportErr(const Token *tok, Severity::SeverityType severity, const std::string &id, const std::string &msg) const
{
std::list<const Token *> callstack;
if (tok)
callstack.push_back(tok);
reportErr(callstack, severity, id, msg);
}
void CheckMemoryLeak::reportErr(const std::list<const Token *> &callstack, Severity::SeverityType severity, const std::string &id, const std::string &msg) const
{
const ErrorLogger::ErrorMessage errmsg(callstack, tokenizer?&tokenizer->list:0, severity, id, msg, false);
if (errorLogger)
errorLogger->reportErr(errmsg);
else
Check::reportError(errmsg);
}
void CheckMemoryLeak::memleakError(const Token *tok, const std::string &varname) const
{
reportErr(tok, Severity::error, "memleak", "Memory leak: " + varname);
}
void CheckMemoryLeak::memleakUponReallocFailureError(const Token *tok, const std::string &varname) const
{
reportErr(tok, Severity::error, "memleakOnRealloc", "Common realloc mistake: \'" + varname + "\' nulled but not freed upon failure");
}
void CheckMemoryLeak::resourceLeakError(const Token *tok, const std::string &varname) const
{
std::string errmsg("Resource leak");
if (!varname.empty())
errmsg += ": " + varname;
reportErr(tok, Severity::error, "resourceLeak", errmsg);
}
void CheckMemoryLeak::deallocDeallocError(const Token *tok, const std::string &varname) const
{
reportErr(tok, Severity::error, "deallocDealloc", "Deallocating a deallocated pointer: " + varname);
}
void CheckMemoryLeak::deallocuseError(const Token *tok, const std::string &varname) const
{
reportErr(tok, Severity::error, "deallocuse", "Dereferencing '" + varname + "' after it is deallocated / released");
}
void CheckMemoryLeak::mismatchSizeError(const Token *tok, const std::string &sz) const
{
reportErr(tok, Severity::error, "mismatchSize", "The given size " + sz + " is mismatching");
}
void CheckMemoryLeak::mismatchAllocDealloc(const std::list<const Token *> &callstack, const std::string &varname) const
{
reportErr(callstack, Severity::error, "mismatchAllocDealloc", "Mismatching allocation and deallocation: " + varname);
}
CheckMemoryLeak::AllocType CheckMemoryLeak::functionReturnType(const Token *tok, std::list<const Token *> *callstack) const
{
if (!tok)
return No;
// Locate start of function
while (tok) {
if (tok->str() == "{" || tok->str() == "}")
return No;
if (tok->str() == "(") {
tok = tok->link();
break;
}
tok = tok->next();
}
// Is this the start of a function?
if (!Token::Match(tok, ") const| {"))
return No;
while (tok->str() != "{")
tok = tok->next();
// Get return pointer..
unsigned int varid = 0;
unsigned int indentlevel = 0;
for (const Token *tok2 = tok; tok2; tok2 = tok2->next()) {
if (tok2->str() == "{")
++indentlevel;
else if (tok2->str() == "}") {
if (indentlevel <= 1)
return No;
--indentlevel;
}
if (Token::Match(tok2, "return %var% ;")) {
if (indentlevel != 1)
return No;
varid = tok2->next()->varId();
break;
} else if (tok2->str() == "return") {
AllocType allocType = getAllocationType(tok2->next(), 0, callstack);
if (allocType != No)
return allocType;
}
}
// Not returning pointer value..
if (varid == 0)
return No;
if (this != NULL) {
// If variable is not local then alloctype shall be "No"
// Todo: there can be false negatives about mismatching allocation/deallocation.
// => Generate "alloc ; use ;" if variable is not local?
const Variable *var = tokenizer->getSymbolDatabase()->getVariableFromVarId(varid);
if (!var || !var->isLocal() || var->isStatic())
return No;
}
// Check if return pointer is allocated..
AllocType allocType = No;
while (NULL != (tok = tok->next())) {
if (Token::Match(tok, "%varid% =", varid)) {
allocType = getAllocationType(tok->tokAt(2), varid, callstack);
}
if (Token::Match(tok, "= %varid% ;", varid)) {
return No;
}
if (Token::Match(tok, "static %type% * %varid% [;{}=]", varid)) {
return No;
}
if (Token::Match(tok, "[(,] %varid% [,)]", varid)) {
return No;
}
if (tok->str() == "return")
return allocType;
}
return allocType;
}
const char *CheckMemoryLeak::functionArgAlloc(const Function *func, unsigned int targetpar, AllocType &allocType) const
{
allocType = No;
if (!func || !func->functionScope)
return "";
std::list<Variable>::const_iterator arg = func->argumentList.begin();
for (; arg != func->argumentList.end(); ++arg) {
if (arg->index() == targetpar-1)
break;
}
if (arg == func->argumentList.end())
return "";
// Is **
if (!arg->isPointer())
return "";
const Token* tok = arg->typeEndToken();
if (tok->str() == "const")
tok = tok->previous();
tok = tok->previous();
if (tok->str() != "*")
return "";
// Check if pointer is allocated.
int realloc = 0;
for (tok = func->functionScope->classStart; tok && tok != func->functionScope->classEnd; tok = tok->next()) {
if (tok->varId() == arg->varId()) {
if (Token::Match(tok->tokAt(-3), "free ( * %var% )")) {
realloc = 1;
allocType = No;
} else if (Token::Match(tok->previous(), "* %var% =")) {
allocType = getAllocationType(tok->tokAt(2), arg->varId());
if (allocType == No) {
allocType = getReallocationType(tok->tokAt(2), arg->varId());
}
if (allocType != No) {
if (realloc)
return "realloc";
return "alloc";
}
} else {
// unhandled variable usage: bailout
return "";
}
}
}
return "";
}
void CheckMemoryLeakInFunction::parse_noreturn()
{
if (noreturn.empty()) {
noreturn.insert("exit");
noreturn.insert("_exit");
noreturn.insert("_Exit");
noreturn.insert("abort");
noreturn.insert("err");
noreturn.insert("verr");
noreturn.insert("errx");
noreturn.insert("verrx");
noreturn.insert("ExitProcess");
noreturn.insert("ExitThread");
noreturn.insert("pthread_exit");
}
std::list<Scope>::const_iterator scope;
for (scope = symbolDatabase->scopeList.begin(); scope != symbolDatabase->scopeList.end(); ++scope) {
// only check functions
if (scope->type != Scope::eFunction)
continue;
// parse this function to check if it contains an "exit" call..
bool isNoreturn = false;
for (const Token *tok2 = scope->classStart->next(); tok2 != scope->classEnd; tok2 = tok2->next()) {
if (Token::Match(tok2->previous(), "[;{}] exit (")) {
isNoreturn = true;
break;
}
}
// This function is not a noreturn function
if (isNoreturn)
noreturn.insert(scope->className);
else
notnoreturn.insert(scope->className);
}
}
bool CheckMemoryLeakInFunction::notvar(const Token *tok, unsigned int varid, bool endpar) const
{
const std::string end(endpar ? " &&|)" : " [;)&|]");
return bool(Token::Match(tok, ("! %varid%" + end).c_str(), varid) ||
Token::Match(tok, ("! ( %varid% )" + end).c_str(), varid));
}
bool CheckMemoryLeakInFunction::test_white_list(const std::string &funcname)
{
return (std::bsearch(funcname.c_str(), call_func_white_list,
sizeof(call_func_white_list) / sizeof(call_func_white_list[0]),
sizeof(call_func_white_list[0]), call_func_white_list_compare) != NULL);
}
const char * CheckMemoryLeakInFunction::call_func(const Token *tok, std::list<const Token *> callstack, const unsigned int varid, AllocType &alloctype, AllocType &dealloctype, bool &allocpar, unsigned int sz)
{
if (test_white_list(tok->str())) {
if (tok->str() == "asprintf" ||
tok->str() == "delete" ||
tok->str() == "fclose" ||
tok->str() == "for" ||
tok->str() == "free" ||
tok->str() == "if" ||
tok->str() == "realloc" ||
tok->str() == "return" ||
tok->str() == "switch" ||
tok->str() == "while") {
return 0;
}
// is the varid a parameter?
for (const Token *tok2 = tok->tokAt(2); tok2 != tok->linkAt(1); tok2 = tok2->next()) {
if (tok2->str() == "(") {
tok2 = tok2->nextArgument();
if (!tok2)
break;
}
if (tok2->varId() == varid) {
if (tok->strAt(-1) == ".")
return "use";
else if (tok2->strAt(1) == "=")
return "assign";
else
return "use_";
}
}
return 0;
}
if (noreturn.find(tok->str()) != noreturn.end() && tok->strAt(-1) != "=")
return "exit";
if (varid > 0 && (getAllocationType(tok, varid) != No || getReallocationType(tok, varid) != No || getDeallocationType(tok, varid) != No))
return 0;
if (callstack.size() > 2)
return "dealloc_";
const std::string& funcname(tok->str());
for (std::list<const Token *>::const_iterator it = callstack.begin(); it != callstack.end(); ++it) {
if ((*it) && (*it)->str() == funcname)
return "recursive";
}
callstack.push_back(tok);
// lock/unlock..
if (varid == 0) {
const Token *ftok = _tokenizer->getFunctionTokenByName(funcname.c_str());
while (ftok && (ftok->str() != "{"))
ftok = ftok->next();
if (!ftok)
return 0;
Token *func = getcode(ftok->next(), callstack, 0, alloctype, dealloctype, false, 1);
simplifycode(func);
const char *ret = 0;
if (Token::simpleMatch(func, "; alloc ; }"))
ret = "alloc";
else if (Token::simpleMatch(func, "; dealloc ; }"))
ret = "dealloc";
TokenList::deleteTokens(func);
return ret;
}
// how many parameters is there in the function call?
unsigned int numpar = countParameters(tok);
if (numpar == 0) {
// Taking return value => it is not a noreturn function
if (tok->strAt(-1) == "=")
return NULL;
// Function is not noreturn
if (notnoreturn.find(funcname) != notnoreturn.end())
return NULL;
return "callfunc";
}
unsigned int par = 0;
const bool dot(tok->previous()->str() == ".");
const bool eq(tok->previous()->str() == "=");
tok = Token::findsimplematch(tok, "(");
if (tok)
tok = tok->next();
for (; tok; tok = tok->nextArgument()) {
++par;
if (varid > 0 && Token::Match(tok, "%varid% [,()]", varid)) {
if (dot)
return "use";
const Token *ftok = _tokenizer->getFunctionTokenByName(funcname.c_str());
if (!ftok)
return "use";
// how many parameters does the function want?
if (numpar != countParameters(ftok))
return "recursive";
const Function* function = _tokenizer->getSymbolDatabase()->findFunctionByToken(ftok);
if (!function)
return "recursive";
const Variable* param = function->getArgumentVar(par-1);
if (!param || !param->nameToken())
return "use";
if (!function->functionScope)
return "use";
Token *func = getcode(function->functionScope->classStart->next(), callstack, param->varId(), alloctype, dealloctype, false, sz);
//simplifycode(func);
const Token *func_ = func;
while (func_ && func_->str() == ";")
func_ = func_->next();
const char *ret = 0;
/** @todo handle "goto" */
if (Token::findsimplematch(func_, "dealloc"))
ret = "dealloc";
else if (Token::findsimplematch(func_, "use"))
ret = "use";
else if (Token::findsimplematch(func_, "&use"))
ret = "&use";
TokenList::deleteTokens(func);
return ret;
}
if (varid > 0 && Token::Match(tok, "& %varid% [,()]", varid)) {
const Token *ftok = _tokenizer->getFunctionTokenByName(funcname.c_str());
if (ftok == 0)
continue;
const Function* func = _tokenizer->getSymbolDatabase()->findFunctionByToken(ftok);
AllocType a;
const char *ret = functionArgAlloc(func, par, a);
if (a != No) {
if (alloctype == No)
alloctype = a;
else if (alloctype != a)
alloctype = Many;
allocpar = true;
return ret;
}
}
if (varid > 0 && Token::Match(tok, "%varid% . %var% [,)]", varid))
return "use";
}
return (eq || _settings->experimental) ? 0 : "callfunc";
}
static void addtoken(Token **rettail, const Token *tok, const std::string &str)
{
(*rettail)->insertToken(str);
(*rettail) = (*rettail)->next();
(*rettail)->linenr(tok->linenr());
(*rettail)->fileIndex(tok->fileIndex());
}
Token *CheckMemoryLeakInFunction::getcode(const Token *tok, std::list<const Token *> callstack, const unsigned int varid, CheckMemoryLeak::AllocType &alloctype, CheckMemoryLeak::AllocType &dealloctype, bool classmember, unsigned int sz)
{
// variables whose value depends on if(!var). If one of these variables
// is used in a if-condition then generate "ifv" instead of "if".
std::set<unsigned int> extravar;
// The first token should be ";"
Token* rethead = new Token(0);
rethead->str(";");
rethead->linenr(tok->linenr());
rethead->fileIndex(tok->fileIndex());
Token* rettail = rethead;
int indentlevel = 0;
int parlevel = 0;
for (; tok; tok = tok->next()) {
if (tok->str() == "{") {
addtoken(&rettail, tok, "{");
++indentlevel;
} else if (tok->str() == "}") {
addtoken(&rettail, tok, "}");
if (indentlevel <= 0)
break;
--indentlevel;
}
else if (tok->str() == "(")
++parlevel;
else if (tok->str() == ")")
--parlevel;
if (parlevel == 0 && tok->str() == ";")
addtoken(&rettail, tok, ";");
// Start of new statement.. check if the statement has anything interesting
if (varid > 0 && parlevel == 0 && Token::Match(tok, "[;{}]")) {
if (Token::Match(tok->next(), "[{};]"))
continue;
// function calls are interesting..
const Token *tok2 = tok;
while (Token::Match(tok2->next(), "%var% ."))
tok2 = tok2->tokAt(2);
if (Token::Match(tok2->next(), "%var% ("))
;
else if (Token::Match(tok->next(), "continue|break|return|throw|goto|do|else"))
;
else {
const Token *skipToToken = 0;
// scan statement for interesting keywords / varid
for (tok2 = tok->next(); tok2; tok2 = tok2->next()) {
if (tok2->str() == ";") {
// nothing interesting found => skip this statement
skipToToken = tok2->previous();
break;
}
if (tok2->varId() == varid ||
tok2->str() == ":" || tok2->str() == "{" || tok2->str() == "}") {
break;
}
}
if (skipToToken) {
tok = skipToToken;
continue;
}
}
}
if (varid == 0) {
if (!callstack.empty() && Token::Match(tok, "[;{}] __cppcheck_lock|__cppcheck_unlock ( ) ;")) {
// Type of leak = Resource leak
alloctype = dealloctype = CheckMemoryLeak::File;
if (tok->next()->str() == "__cppcheck_lock") {
addtoken(&rettail, tok, "alloc");
} else {
addtoken(&rettail, tok, "dealloc");
}
tok = tok->tokAt(3);
continue;
}
if (Token::simpleMatch(tok, "if (")) {
addtoken(&rettail, tok, "if");
tok = tok->next()->link();
continue;
}
} else {
if (Token::Match(tok, "%varid% = close ( %varid% )", varid)) {
addtoken(&rettail, tok, "dealloc");
addtoken(&rettail, tok, ";");
addtoken(&rettail, tok, "assign");
addtoken(&rettail, tok, ";");
tok = tok->tokAt(5);
continue;
}
// var = strcpy|.. ( var ,
if (Token::Match(tok, "[;{}] %varid% = memcpy|memmove|memset|strcpy|strncpy|strcat|strncat ( %varid% ,", varid)) {
tok = tok->linkAt(4);
continue;
}
if (Token::Match(tok->previous(), "[(;{}] %varid% =", varid) ||
Token::Match(tok, "asprintf|vasprintf ( & %varid% ,", varid)) {
CheckMemoryLeak::AllocType alloc;
if (Token::Match(tok, "asprintf|vasprintf (")) {
// todo: check how the return value is used.
if (!Token::Match(tok->previous(), "[;{}]")) {
TokenList::deleteTokens(rethead);
return 0;
}
alloc = Malloc;
tok = tok->next()->link();
} else {
alloc = getAllocationType(tok->tokAt(2), varid);
}
bool realloc = false;
if (sz > 1 &&
Token::Match(tok->tokAt(2), "malloc ( %num% )") &&
(MathLib::toLongNumber(tok->strAt(4)) % long(sz)) != 0) {
mismatchSizeError(tok->tokAt(4), tok->strAt(4));
}
if (alloc == CheckMemoryLeak::No) {
alloc = getReallocationType(tok->tokAt(2), varid);
if (alloc != CheckMemoryLeak::No) {
addtoken(&rettail, tok, "realloc");
addtoken(&rettail, tok, ";");
realloc = true;
tok = tok->tokAt(2);
if (Token::Match(tok, "%var% ("))
tok = tok->next()->link();
continue;
}
}
// don't check classes..
if (alloc == CheckMemoryLeak::New) {
if (Token::Match(tok->tokAt(2), "new struct| %type% [(;]")) {
const int offset = tok->strAt(3) == "struct" ? 1 : 0;
if (isclass(_tokenizer, tok->tokAt(3 + offset), varid)) {
alloc = No;
}
} else if (Token::Match(tok->tokAt(2), "new ( nothrow ) struct| %type%")) {
const int offset = tok->strAt(6) == "struct" ? 1 : 0;
if (isclass(_tokenizer, tok->tokAt(6 + offset), varid)) {
alloc = No;
}
} else if (Token::Match(tok->tokAt(2), "new ( std :: nothrow ) struct| %type%")) {
const int offset = tok->strAt(8) == "struct" ? 1 : 0;
if (isclass(_tokenizer, tok->tokAt(8 + offset), varid)) {
alloc = No;
}
}
if (alloc == No && alloctype == No)
alloctype = CheckMemoryLeak::New;
}
if (alloc != No) {
if (! realloc)
addtoken(&rettail, tok, "alloc");
if (alloctype != No && alloctype != alloc)
alloc = Many;
if (alloc != Many && dealloctype != No && dealloctype != Many && dealloctype != alloc) {
callstack.push_back(tok);
mismatchAllocDealloc(callstack, Token::findmatch(_tokenizer->tokens(), "%varid%", varid)->str());
callstack.pop_back();
}
alloctype = alloc;
if (Token::Match(tok, "%var% = %type% (")) {
tok = tok->linkAt(3);
continue;
}
}
// assignment..
else {
// is the pointer in rhs?
bool rhs = false;
for (const Token *tok2 = tok->next(); tok2; tok2 = tok2->next()) {
if (tok2->str() == ";") {
if (rhs)
tok = tok2;
break;
}
if (Token::Match(tok2, "[=+(,] %varid%", varid)) {
if (!rhs && Token::Match(tok2, "[(,]")) {
addtoken(&rettail, tok, "use");
addtoken(&rettail, tok, ";");
}
rhs = true;
}
}
if (!rhs)
addtoken(&rettail, tok, "assign");
continue;
}
}
if (Token::Match(tok->previous(), "[;{})=|] ::| %var%")) {
if (Token::Match(tok, "%varid% ?", varid))
tok = tok->tokAt(2);
AllocType dealloc = getDeallocationType(tok, varid);
if (dealloc != No && tok->str() == "fcloseall" && alloctype != dealloc)
dealloc = No;
else if (dealloc != No) {
addtoken(&rettail, tok, "dealloc");