Cppcheck
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Groups Pages
checkmemoryleak.h
Go to the documentation of this file.
1 /*
2  * Cppcheck - A tool for static C/C++ code analysis
3  * Copyright (C) 2007-2015 Daniel Marjamäki and Cppcheck team.
4  *
5  * This program is free software: you can redistribute it and/or modify
6  * it under the terms of the GNU General Public License as published by
7  * the Free Software Foundation, either version 3 of the License, or
8  * (at your option) any later version.
9  *
10  * This program is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13  * GNU General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public License
16  * along with this program. If not, see <http://www.gnu.org/licenses/>.
17  */
18 
19 //---------------------------------------------------------------------------
20 #ifndef checkmemoryleakH
21 #define checkmemoryleakH
22 //---------------------------------------------------------------------------
23 
24 /**
25  * @file
26  *
27  * %Check for memory leaks
28  *
29  * The checking is split up into three specialized classes.
30  * - CheckMemoryLeakInFunction can detect when a function variable is allocated but not deallocated properly.
31  * - CheckMemoryLeakInClass can detect when a class variable is allocated but not deallocated properly.
32  * - CheckMemoryLeakStructMember checks allocation/deallocation of structs and struct members
33  */
34 
35 #include "config.h"
36 #include "check.h"
37 
38 #include <list>
39 #include <string>
40 
41 class Scope;
42 class Function;
43 class Variable;
44 
45 /// @addtogroup Core
46 /// @{
47 
48 /** @brief Base class for memory leaks checking */
50 protected:
51  /** For access to the tokens */
52  const Tokenizer * const tokenizer;
53 
54 private:
55  /** ErrorLogger used to report errors */
57 
58  /** Enabled standards */
59  const Settings * const settings1;
60 
61  /** Disable the default constructors */
63 
64  /** Disable the default constructors */
66 
67  /** disable assignment operator */
68  void operator=(const CheckMemoryLeak &);
69 
70  /**
71  * Report error. Similar with the function Check::reportError
72  * @param location the token where the error occurs
73  * @param severity the severity of the bug
74  * @param id type of message
75  * @param msg text
76  * @param cwe cwe number
77  */
78  void reportErr(const Token *location, Severity::SeverityType severity, const std::string &id, const std::string &msg, unsigned int cwe) const;
79 
80  /**
81  * Report error. Similar with the function Check::reportError
82  * @param callstack callstack of error
83  * @param severity the severity of the bug
84  * @param id type of message
85  * @param msg text
86  * @param cwe cwe number
87  */
88  void reportErr(const std::list<const Token *> &callstack, Severity::SeverityType severity, const std::string &id, const std::string &msg, unsigned int cwe) const;
89 
90 public:
92  : tokenizer(t), errorLogger(e), settings1(s) {
93  }
94 
95  /** @brief What type of allocation are used.. the "Many" means that several types of allocation and deallocation are used */
96  enum AllocType { No, Malloc, New, NewArray, File, Fd, Pipe, OtherMem, OtherRes, Many };
97 
98  void memoryLeak(const Token *tok, const std::string &varname, AllocType alloctype);
99 
100  /**
101  * @brief Get type of deallocation at given position
102  * @param tok position
103  * @param varname variable name
104  * @return type of deallocation
105  */
106  AllocType getDeallocationType(const Token *tok, const std::string &varname) const;
107 
108  /**
109  * @brief Get type of deallocation at given position
110  * @param tok position
111  * @param varid variable id
112  * @return type of deallocation
113  */
114  AllocType getDeallocationType(const Token *tok, unsigned int varid) const;
115 
116  /**
117  * @brief Get type of allocation at given position
118  */
119  AllocType getAllocationType(const Token *tok2, unsigned int varid, std::list<const Function*> *callstack = NULL) const;
120 
121  /**
122  * @brief Get type of reallocation at given position
123  */
124  static AllocType getReallocationType(const Token *tok2, unsigned int varid);
125 
126  /**
127  * @brief Is a typename the name of a class?
128  * @param tok type token
129  * @param varid variable id
130  * @return true if the type name is the name of a class
131  */
132  bool isclass(const Token *tok, unsigned int varid) const;
133 
134  /**
135  * Report that there is a memory leak (new/malloc/etc)
136  * @param tok token where memory is leaked
137  * @param varname name of variable
138  */
139  void memleakError(const Token *tok, const std::string &varname) const;
140 
141  /**
142  * Report that there is a resource leak (fopen/popen/etc)
143  * @param tok token where resource is leaked
144  * @param varname name of variable
145  */
146  void resourceLeakError(const Token *tok, const std::string &varname) const;
147 
148  /**
149  * @brief Report error: deallocating a deallocated pointer
150  * @param tok token where error occurs
151  * @param varname name of variable
152  */
153  void deallocDeallocError(const Token *tok, const std::string &varname) const;
154  void deallocuseError(const Token *tok, const std::string &varname) const;
155  void mismatchSizeError(const Token *tok, const std::string &sz) const;
156  void mismatchAllocDealloc(const std::list<const Token *> &callstack, const std::string &varname) const;
157  void memleakUponReallocFailureError(const Token *tok, const std::string &varname) const;
158 
159  /** What type of allocated memory does the given function return? */
160  AllocType functionReturnType(const Function* func, std::list<const Function*> *callstack = NULL) const;
161 
162  /** Function allocates pointed-to argument (a la asprintf)? */
163  const char *functionArgAlloc(const Function *func, unsigned int targetpar, AllocType &allocType) const;
164 };
165 
166 /// @}
167 
168 
169 
170 /// @addtogroup Checks
171 /// @{
172 
173 
174 /**
175  * @brief %CheckMemoryLeakInFunction detects when a function variable is allocated but not deallocated properly.
176  *
177  * The checking is done by looking at each function variable separately. By repeating these 4 steps over and over:
178  * -# locate a function variable
179  * -# create a simple token list that describes the usage of the function variable.
180  * -# simplify the token list.
181  * -# finally, check if the simplified token list contain any leaks.
182  */
183 
185 public:
186  /** @brief This constructor is used when registering this class */
187  CheckMemoryLeakInFunction() : Check(myName()), CheckMemoryLeak(0, 0, 0), symbolDatabase(NULL) {
188  }
189 
190  /** @brief This constructor is used when running checks */
191  CheckMemoryLeakInFunction(const Tokenizer *tokenizr, const Settings *settings, ErrorLogger *errLog)
192  : Check(myName(), tokenizr, settings, errLog), CheckMemoryLeak(tokenizr, errLog, settings) {
193  // get the symbol database
194  if (tokenizr)
195  symbolDatabase = tokenizr->getSymbolDatabase();
196  else
197  symbolDatabase = 0;
198  }
199 
200  /** @brief run all simplified checks */
201  void runSimplifiedChecks(const Tokenizer *tokenizr, const Settings *settings, ErrorLogger *errLog) {
202  CheckMemoryLeakInFunction checkMemoryLeak(tokenizr, settings, errLog);
203  checkMemoryLeak.checkReallocUsage();
204  checkMemoryLeak.check();
205  }
206 
207  /** @brief Unit testing : testing the white list */
208  static bool test_white_list(const std::string &funcname, const Settings *settings, bool cpp);
209 
210  /** @brief Perform checking */
211  void check();
212 
213  /**
214  * Checking for a memory leak caused by improper realloc usage.
215  */
216  void checkReallocUsage();
217 
218  /**
219  * @brief %Check if there is a "!var" match inside a condition
220  * @param tok first token to match
221  * @param varid variable id
222  * @param endpar if this is true the "!var" must be followed by ")"
223  * @return true if match
224  */
225  static bool notvar(const Token *tok, unsigned int varid, bool endpar = false);
226 
227  /**
228  * Inspect a function call. the call_func and getcode are recursive
229  * @param tok token where the function call occurs
230  * @param callstack callstack
231  * @param varid variable id to check
232  * @param alloctype if memory is allocated, this indicates the type of allocation
233  * @param dealloctype if memory is deallocated, this indicates the type of deallocation
234  * @param allocpar if function allocates varid parameter
235  * @param sz not used by call_func - see getcode
236  * @return These are the possible return values:
237  * - NULL : no significant code
238  * - "recursive" : recursive function
239  * - "alloc" : the function returns allocated memory
240  * - "dealloc" : the function deallocates the variable
241  * - "dealloc_"
242  * - "use" : the variable is used (unknown usage of the variable => the checking bails out)
243  * - "callfunc" : a function call with unknown side effects
244  * - "&use"
245  */
246  const char * call_func(const Token *tok, std::list<const Token *> callstack, const unsigned int varid, AllocType &alloctype, AllocType &dealloctype, bool &allocpar, unsigned int sz);
247 
248  /**
249  * Extract a new tokens list that is easier to parse than the "_tokenizer->tokens()", the
250  * extracted tokens list describes how the given variable is used.
251  * The getcode and call_func are recursive
252  * @param tok start parse token
253  * @param callstack callstack
254  * @param varid variable id
255  * @param alloctype keep track of what type of allocation is used
256  * @param dealloctype keeps track of what type of deallocation is used
257  * @param classmember should be set if the inspected function is a class member
258  * @param sz size of type, used to check for mismatching size of allocation. for example "int *a;" => the sz is "sizeof(int)"
259  * @return Newly allocated token array. Caller needs to release reserved
260  * memory by calling TokenList::deleteTokens(returnValue);
261  * Returned tokens:
262  * - "alloc" : the variable is allocated
263  * - "assign" : the variable is assigned a new value
264  * - "break" : corresponds to "break"
265  * - "callfunc" : a function call with unknown side effects
266  * - "continue" : corresponds to "continue"
267  * - "dealloc" : the variable is deallocated
268  * - "goto" : corresponds to a "goto"
269  * - "if" : there is an "if"
270  * - "if(var)" : corresponds with "if ( var != 0 )"
271  * - "if(!var)" : corresponds with "if ( var == 0 )"
272  * - "ifv" : the variable is used in some way in a "if"
273  * - "loop" : corresponds to either a "for" or a "while"
274  * - "realloc" : the variable is reallocated
275  * - "return" : corresponds to a "return"
276  * - "use" : unknown usage -> bail out checking of this execution path
277  * - "&use" : the address of the variable is taken
278  * - "::use" : calling member function of class
279  * - "use_" : content of variable is accessed (used to warn access after dealloc)
280  */
281  Token *getcode(const Token *tok, std::list<const Token *> callstack, const unsigned int varid, AllocType &alloctype, AllocType &dealloctype, bool classmember, unsigned int sz);
282 
283  /**
284  * Simplify code e.g. by replacing empty "{ }" with ";"
285  * @param tok first token. The tokens list can be modified.
286  */
287  void simplifycode(Token *tok) const;
288 
289  static const Token *findleak(const Token *tokens);
290 
291  /**
292  * Checking the variable varname
293  * @param startTok start token
294  * @param varname name of variable (for error messages)
295  * @param varid variable id
296  * @param classmember is the scope inside a class member function
297  * @param sz size of type.. if the variable is a "int *" then sz should be "sizeof(int)"
298  */
299  void checkScope(const Token *startTok, const std::string &varname, unsigned int varid, bool classmember, unsigned int sz);
300 
301 private:
302  /** Report all possible errors (for the --errorlist) */
303  void getErrorMessages(ErrorLogger *e, const Settings *settings) const {
304  CheckMemoryLeakInFunction c(0, settings, e);
305 
306  c.memleakError(0, "varname");
307  c.resourceLeakError(0, "varname");
308 
309  c.deallocDeallocError(0, "varname");
310  c.deallocuseError(0, "varname");
311  c.mismatchSizeError(0, "sz");
312  std::list<const Token *> callstack;
313  c.mismatchAllocDealloc(callstack, "varname");
314  c.memleakUponReallocFailureError(0, "varname");
315  }
316 
317  /**
318  * Get name of class (--doc)
319  * @return name of class
320  */
321  static std::string myName() {
322  return "Memory leaks (function variables)";
323  }
324 
325  /**
326  * Get class information (--doc)
327  * @return Wiki formatted information about this class
328  */
329  std::string classInfo() const {
330  return "Is there any allocated memory when a function goes out of scope\n";
331  }
332 
334 };
335 
336 
337 
338 /**
339  * @brief %Check class variables, variables that are allocated in the constructor should be deallocated in the destructor
340  */
341 
343 public:
344  CheckMemoryLeakInClass() : Check(myName()), CheckMemoryLeak(0, 0, 0) {
345  }
346 
347  CheckMemoryLeakInClass(const Tokenizer *tokenizr, const Settings *settings, ErrorLogger *errLog)
348  : Check(myName(), tokenizr, settings, errLog), CheckMemoryLeak(tokenizr, errLog, settings) {
349  }
350 
351  void runSimplifiedChecks(const Tokenizer *tokenizr, const Settings *settings, ErrorLogger *errLog) {
352  if (!tokenizr->isCPP())
353  return;
354 
355  CheckMemoryLeakInClass checkMemoryLeak(tokenizr, settings, errLog);
356  checkMemoryLeak.check();
357  }
358 
359  void check();
360 
361 private:
362  void variable(const Scope *scope, const Token *tokVarname);
363 
364  /** Public functions: possible double-allocation */
365  void checkPublicFunctions(const Scope *scope, const Token *classtok);
366  void publicAllocationError(const Token *tok, const std::string &varname);
367 
368  void unsafeClassError(const Token *tok, const std::string &classname, const std::string &varname);
369 
370  void getErrorMessages(ErrorLogger *e, const Settings *settings) const {
371  CheckMemoryLeakInClass c(0, settings, e);
372  c.publicAllocationError(0, "varname");
373  c.unsafeClassError(0, "class", "class::varname");
374  }
375 
376  static std::string myName() {
377  return "Memory leaks (class variables)";
378  }
379 
380  std::string classInfo() const {
381  return "If the constructor allocate memory then the destructor must deallocate it.\n";
382  }
383 };
384 
385 
386 
387 /** @brief detect simple memory leaks for struct members */
388 
390 public:
392  }
393 
394  CheckMemoryLeakStructMember(const Tokenizer *tokenizr, const Settings *settings, ErrorLogger *errLog)
395  : Check(myName(), tokenizr, settings, errLog), CheckMemoryLeak(tokenizr, errLog, settings) {
396  }
397 
398  void runSimplifiedChecks(const Tokenizer *tokenizr, const Settings *settings, ErrorLogger *errLog) {
399  CheckMemoryLeakStructMember checkMemoryLeak(tokenizr, settings, errLog);
400  checkMemoryLeak.check();
401  }
402 
403  void check();
404 
405 private:
406 
407  /** Is local variable allocated with malloc? */
408  static bool isMalloc(const Variable *variable);
409 
410  void checkStructVariable(const Variable * const variable);
411 
412  void getErrorMessages(ErrorLogger * /*errorLogger*/, const Settings * /*settings*/) const {
413  }
414 
415  static std::string myName() {
416  return "Memory leaks (struct members)";
417  }
418 
419  std::string classInfo() const {
420  return "Don't forget to deallocate struct members\n";
421  }
422 };
423 
424 
425 
426 /** @brief detect simple memory leaks (address not taken) */
427 
429 public:
430  CheckMemoryLeakNoVar() : Check(myName()), CheckMemoryLeak(0, 0, 0) {
431  }
432 
433  CheckMemoryLeakNoVar(const Tokenizer *tokenizr, const Settings *settings, ErrorLogger *errLog)
434  : Check(myName(), tokenizr, settings, errLog), CheckMemoryLeak(tokenizr, errLog, settings) {
435  }
436 
437  void runSimplifiedChecks(const Tokenizer *tokenizr, const Settings *settings, ErrorLogger *errLog) {
438  CheckMemoryLeakNoVar checkMemoryLeak(tokenizr, settings, errLog);
439  checkMemoryLeak.check();
440  }
441 
442  void check();
443 
444 private:
445  /**
446  * @brief %Check if a call to an allocation function like malloc() is made and its return value is not assigned.
447  * @param scope The scope of the function to check.
448  */
449  void checkForUnusedReturnValue(const Scope *scope);
450 
451  /**
452  * @brief %Check if an exception could cause a leak in an argument constructed with shared_ptr/unique_ptr.
453  * @param scope The scope of the function to check.
454  */
455  void checkForUnsafeArgAlloc(const Scope *scope);
456 
457  void functionCallLeak(const Token *loc, const std::string &alloc, const std::string &functionCall);
458  void returnValueNotUsedError(const Token* tok, const std::string &alloc);
459  void unsafeArgAllocError(const Token *tok, const std::string &funcName, const std::string &ptrType, const std::string &objType);
460 
461  void getErrorMessages(ErrorLogger *e, const Settings *settings) const {
462  CheckMemoryLeakNoVar c(0, settings, e);
463 
464  c.functionCallLeak(0, "funcName", "funcName");
465  c.returnValueNotUsedError(0, "funcName");
466  c.unsafeArgAllocError(0, "funcName", "shared_ptr", "int");
467  }
468 
469  static std::string myName() {
470  return "Memory leaks (address not taken)";
471  }
472 
473  std::string classInfo() const {
474  return "Not taking the address to allocated memory\n";
475  }
476 };
477 /// @}
478 //---------------------------------------------------------------------------
479 #endif // checkmemoryleakH