MallocChecker.cpp 98 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734
  1. //=== MallocChecker.cpp - A malloc/free checker -------------------*- C++ -*--//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. //
  10. // This file defines malloc/free checker, which checks for potential memory
  11. // leaks, double free, and use-after-free problems.
  12. //
  13. //===----------------------------------------------------------------------===//
  14. #include "ClangSACheckers.h"
  15. #include "InterCheckerAPI.h"
  16. #include "clang/AST/Attr.h"
  17. #include "clang/AST/ParentMap.h"
  18. #include "clang/Basic/SourceManager.h"
  19. #include "clang/Basic/TargetInfo.h"
  20. #include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
  21. #include "clang/StaticAnalyzer/Core/Checker.h"
  22. #include "clang/StaticAnalyzer/Core/CheckerManager.h"
  23. #include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h"
  24. #include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
  25. #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h"
  26. #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramStateTrait.h"
  27. #include "clang/StaticAnalyzer/Core/PathSensitive/SymbolManager.h"
  28. #include "llvm/ADT/ImmutableMap.h"
  29. #include "llvm/ADT/STLExtras.h"
  30. #include "llvm/ADT/SmallString.h"
  31. #include "llvm/ADT/StringExtras.h"
  32. #include <climits>
  33. using namespace clang;
  34. using namespace ento;
  35. namespace {
  36. // Used to check correspondence between allocators and deallocators.
  37. enum AllocationFamily {
  38. AF_None,
  39. AF_Malloc,
  40. AF_CXXNew,
  41. AF_CXXNewArray,
  42. AF_IfNameIndex,
  43. AF_Alloca
  44. };
  45. class RefState {
  46. enum Kind { // Reference to allocated memory.
  47. Allocated,
  48. // Reference to zero-allocated memory.
  49. AllocatedOfSizeZero,
  50. // Reference to released/freed memory.
  51. Released,
  52. // The responsibility for freeing resources has transferred from
  53. // this reference. A relinquished symbol should not be freed.
  54. Relinquished,
  55. // We are no longer guaranteed to have observed all manipulations
  56. // of this pointer/memory. For example, it could have been
  57. // passed as a parameter to an opaque function.
  58. Escaped
  59. };
  60. const Stmt *S;
  61. unsigned K : 3; // Kind enum, but stored as a bitfield.
  62. unsigned Family : 29; // Rest of 32-bit word, currently just an allocation
  63. // family.
  64. RefState(Kind k, const Stmt *s, unsigned family)
  65. : S(s), K(k), Family(family) {
  66. assert(family != AF_None);
  67. }
  68. public:
  69. bool isAllocated() const { return K == Allocated; }
  70. bool isAllocatedOfSizeZero() const { return K == AllocatedOfSizeZero; }
  71. bool isReleased() const { return K == Released; }
  72. bool isRelinquished() const { return K == Relinquished; }
  73. bool isEscaped() const { return K == Escaped; }
  74. AllocationFamily getAllocationFamily() const {
  75. return (AllocationFamily)Family;
  76. }
  77. const Stmt *getStmt() const { return S; }
  78. bool operator==(const RefState &X) const {
  79. return K == X.K && S == X.S && Family == X.Family;
  80. }
  81. static RefState getAllocated(unsigned family, const Stmt *s) {
  82. return RefState(Allocated, s, family);
  83. }
  84. static RefState getAllocatedOfSizeZero(const RefState *RS) {
  85. return RefState(AllocatedOfSizeZero, RS->getStmt(),
  86. RS->getAllocationFamily());
  87. }
  88. static RefState getReleased(unsigned family, const Stmt *s) {
  89. return RefState(Released, s, family);
  90. }
  91. static RefState getRelinquished(unsigned family, const Stmt *s) {
  92. return RefState(Relinquished, s, family);
  93. }
  94. static RefState getEscaped(const RefState *RS) {
  95. return RefState(Escaped, RS->getStmt(), RS->getAllocationFamily());
  96. }
  97. void Profile(llvm::FoldingSetNodeID &ID) const {
  98. ID.AddInteger(K);
  99. ID.AddPointer(S);
  100. ID.AddInteger(Family);
  101. }
  102. void dump(raw_ostream &OS) const {
  103. switch (static_cast<Kind>(K)) {
  104. #define CASE(ID) case ID: OS << #ID; break;
  105. CASE(Allocated)
  106. CASE(AllocatedOfSizeZero)
  107. CASE(Released)
  108. CASE(Relinquished)
  109. CASE(Escaped)
  110. }
  111. }
  112. LLVM_DUMP_METHOD void dump() const { dump(llvm::errs()); }
  113. };
  114. enum ReallocPairKind {
  115. RPToBeFreedAfterFailure,
  116. // The symbol has been freed when reallocation failed.
  117. RPIsFreeOnFailure,
  118. // The symbol does not need to be freed after reallocation fails.
  119. RPDoNotTrackAfterFailure
  120. };
  121. /// \class ReallocPair
  122. /// \brief Stores information about the symbol being reallocated by a call to
  123. /// 'realloc' to allow modeling failed reallocation later in the path.
  124. struct ReallocPair {
  125. // \brief The symbol which realloc reallocated.
  126. SymbolRef ReallocatedSym;
  127. ReallocPairKind Kind;
  128. ReallocPair(SymbolRef S, ReallocPairKind K) :
  129. ReallocatedSym(S), Kind(K) {}
  130. void Profile(llvm::FoldingSetNodeID &ID) const {
  131. ID.AddInteger(Kind);
  132. ID.AddPointer(ReallocatedSym);
  133. }
  134. bool operator==(const ReallocPair &X) const {
  135. return ReallocatedSym == X.ReallocatedSym &&
  136. Kind == X.Kind;
  137. }
  138. };
  139. typedef std::pair<const ExplodedNode*, const MemRegion*> LeakInfo;
  140. class MallocChecker : public Checker<check::DeadSymbols,
  141. check::PointerEscape,
  142. check::ConstPointerEscape,
  143. check::PreStmt<ReturnStmt>,
  144. check::PreCall,
  145. check::PostStmt<CallExpr>,
  146. check::PostStmt<CXXNewExpr>,
  147. check::PreStmt<CXXDeleteExpr>,
  148. check::PostStmt<BlockExpr>,
  149. check::PostObjCMessage,
  150. check::Location,
  151. eval::Assume>
  152. {
  153. public:
  154. MallocChecker()
  155. : II_alloca(nullptr), II_malloc(nullptr), II_free(nullptr),
  156. II_realloc(nullptr), II_calloc(nullptr), II_valloc(nullptr),
  157. II_reallocf(nullptr), II_strndup(nullptr), II_strdup(nullptr),
  158. II_kmalloc(nullptr), II_if_nameindex(nullptr),
  159. II_if_freenameindex(nullptr) {}
  160. /// In pessimistic mode, the checker assumes that it does not know which
  161. /// functions might free the memory.
  162. enum CheckKind {
  163. CK_MallocChecker,
  164. CK_NewDeleteChecker,
  165. CK_NewDeleteLeaksChecker,
  166. CK_MismatchedDeallocatorChecker,
  167. CK_NumCheckKinds
  168. };
  169. enum class MemoryOperationKind {
  170. MOK_Allocate,
  171. MOK_Free,
  172. MOK_Any
  173. };
  174. DefaultBool IsOptimistic;
  175. DefaultBool ChecksEnabled[CK_NumCheckKinds];
  176. CheckName CheckNames[CK_NumCheckKinds];
  177. void checkPreCall(const CallEvent &Call, CheckerContext &C) const;
  178. void checkPostStmt(const CallExpr *CE, CheckerContext &C) const;
  179. void checkPostStmt(const CXXNewExpr *NE, CheckerContext &C) const;
  180. void checkPreStmt(const CXXDeleteExpr *DE, CheckerContext &C) const;
  181. void checkPostObjCMessage(const ObjCMethodCall &Call, CheckerContext &C) const;
  182. void checkPostStmt(const BlockExpr *BE, CheckerContext &C) const;
  183. void checkDeadSymbols(SymbolReaper &SymReaper, CheckerContext &C) const;
  184. void checkPreStmt(const ReturnStmt *S, CheckerContext &C) const;
  185. ProgramStateRef evalAssume(ProgramStateRef state, SVal Cond,
  186. bool Assumption) const;
  187. void checkLocation(SVal l, bool isLoad, const Stmt *S,
  188. CheckerContext &C) const;
  189. ProgramStateRef checkPointerEscape(ProgramStateRef State,
  190. const InvalidatedSymbols &Escaped,
  191. const CallEvent *Call,
  192. PointerEscapeKind Kind) const;
  193. ProgramStateRef checkConstPointerEscape(ProgramStateRef State,
  194. const InvalidatedSymbols &Escaped,
  195. const CallEvent *Call,
  196. PointerEscapeKind Kind) const;
  197. void printState(raw_ostream &Out, ProgramStateRef State,
  198. const char *NL, const char *Sep) const override;
  199. private:
  200. mutable std::unique_ptr<BugType> BT_DoubleFree[CK_NumCheckKinds];
  201. mutable std::unique_ptr<BugType> BT_DoubleDelete;
  202. mutable std::unique_ptr<BugType> BT_Leak[CK_NumCheckKinds];
  203. mutable std::unique_ptr<BugType> BT_UseFree[CK_NumCheckKinds];
  204. mutable std::unique_ptr<BugType> BT_BadFree[CK_NumCheckKinds];
  205. mutable std::unique_ptr<BugType> BT_FreeAlloca[CK_NumCheckKinds];
  206. mutable std::unique_ptr<BugType> BT_MismatchedDealloc;
  207. mutable std::unique_ptr<BugType> BT_OffsetFree[CK_NumCheckKinds];
  208. mutable std::unique_ptr<BugType> BT_UseZerroAllocated[CK_NumCheckKinds];
  209. mutable IdentifierInfo *II_alloca, *II_malloc, *II_free, *II_realloc,
  210. *II_calloc, *II_valloc, *II_reallocf, *II_strndup,
  211. *II_strdup, *II_kmalloc, *II_if_nameindex,
  212. *II_if_freenameindex;
  213. mutable Optional<uint64_t> KernelZeroFlagVal;
  214. void initIdentifierInfo(ASTContext &C) const;
  215. /// \brief Determine family of a deallocation expression.
  216. AllocationFamily getAllocationFamily(CheckerContext &C, const Stmt *S) const;
  217. /// \brief Print names of allocators and deallocators.
  218. ///
  219. /// \returns true on success.
  220. bool printAllocDeallocName(raw_ostream &os, CheckerContext &C,
  221. const Expr *E) const;
  222. /// \brief Print expected name of an allocator based on the deallocator's
  223. /// family derived from the DeallocExpr.
  224. void printExpectedAllocName(raw_ostream &os, CheckerContext &C,
  225. const Expr *DeallocExpr) const;
  226. /// \brief Print expected name of a deallocator based on the allocator's
  227. /// family.
  228. void printExpectedDeallocName(raw_ostream &os, AllocationFamily Family) const;
  229. ///@{
  230. /// Check if this is one of the functions which can allocate/reallocate memory
  231. /// pointed to by one of its arguments.
  232. bool isMemFunction(const FunctionDecl *FD, ASTContext &C) const;
  233. bool isCMemFunction(const FunctionDecl *FD,
  234. ASTContext &C,
  235. AllocationFamily Family,
  236. MemoryOperationKind MemKind) const;
  237. bool isStandardNewDelete(const FunctionDecl *FD, ASTContext &C) const;
  238. ///@}
  239. /// \brief Perform a zero-allocation check.
  240. ProgramStateRef ProcessZeroAllocation(CheckerContext &C, const Expr *E,
  241. const unsigned AllocationSizeArg,
  242. ProgramStateRef State) const;
  243. ProgramStateRef MallocMemReturnsAttr(CheckerContext &C,
  244. const CallExpr *CE,
  245. const OwnershipAttr* Att,
  246. ProgramStateRef State) const;
  247. static ProgramStateRef MallocMemAux(CheckerContext &C, const CallExpr *CE,
  248. const Expr *SizeEx, SVal Init,
  249. ProgramStateRef State,
  250. AllocationFamily Family = AF_Malloc);
  251. static ProgramStateRef MallocMemAux(CheckerContext &C, const CallExpr *CE,
  252. SVal SizeEx, SVal Init,
  253. ProgramStateRef State,
  254. AllocationFamily Family = AF_Malloc);
  255. // Check if this malloc() for special flags. At present that means M_ZERO or
  256. // __GFP_ZERO (in which case, treat it like calloc).
  257. llvm::Optional<ProgramStateRef>
  258. performKernelMalloc(const CallExpr *CE, CheckerContext &C,
  259. const ProgramStateRef &State) const;
  260. /// Update the RefState to reflect the new memory allocation.
  261. static ProgramStateRef
  262. MallocUpdateRefState(CheckerContext &C, const Expr *E, ProgramStateRef State,
  263. AllocationFamily Family = AF_Malloc);
  264. ProgramStateRef FreeMemAttr(CheckerContext &C, const CallExpr *CE,
  265. const OwnershipAttr* Att,
  266. ProgramStateRef State) const;
  267. ProgramStateRef FreeMemAux(CheckerContext &C, const CallExpr *CE,
  268. ProgramStateRef state, unsigned Num,
  269. bool Hold,
  270. bool &ReleasedAllocated,
  271. bool ReturnsNullOnFailure = false) const;
  272. ProgramStateRef FreeMemAux(CheckerContext &C, const Expr *Arg,
  273. const Expr *ParentExpr,
  274. ProgramStateRef State,
  275. bool Hold,
  276. bool &ReleasedAllocated,
  277. bool ReturnsNullOnFailure = false) const;
  278. ProgramStateRef ReallocMem(CheckerContext &C, const CallExpr *CE,
  279. bool FreesMemOnFailure,
  280. ProgramStateRef State) const;
  281. static ProgramStateRef CallocMem(CheckerContext &C, const CallExpr *CE,
  282. ProgramStateRef State);
  283. ///\brief Check if the memory associated with this symbol was released.
  284. bool isReleased(SymbolRef Sym, CheckerContext &C) const;
  285. bool checkUseAfterFree(SymbolRef Sym, CheckerContext &C, const Stmt *S) const;
  286. void checkUseZeroAllocated(SymbolRef Sym, CheckerContext &C,
  287. const Stmt *S) const;
  288. bool checkDoubleDelete(SymbolRef Sym, CheckerContext &C) const;
  289. /// Check if the function is known free memory, or if it is
  290. /// "interesting" and should be modeled explicitly.
  291. ///
  292. /// \param [out] EscapingSymbol A function might not free memory in general,
  293. /// but could be known to free a particular symbol. In this case, false is
  294. /// returned and the single escaping symbol is returned through the out
  295. /// parameter.
  296. ///
  297. /// We assume that pointers do not escape through calls to system functions
  298. /// not handled by this checker.
  299. bool mayFreeAnyEscapedMemoryOrIsModeledExplicitly(const CallEvent *Call,
  300. ProgramStateRef State,
  301. SymbolRef &EscapingSymbol) const;
  302. // Implementation of the checkPointerEscape callabcks.
  303. ProgramStateRef checkPointerEscapeAux(ProgramStateRef State,
  304. const InvalidatedSymbols &Escaped,
  305. const CallEvent *Call,
  306. PointerEscapeKind Kind,
  307. bool(*CheckRefState)(const RefState*)) const;
  308. ///@{
  309. /// Tells if a given family/call/symbol is tracked by the current checker.
  310. /// Sets CheckKind to the kind of the checker responsible for this
  311. /// family/call/symbol.
  312. Optional<CheckKind> getCheckIfTracked(AllocationFamily Family,
  313. bool IsALeakCheck = false) const;
  314. Optional<CheckKind> getCheckIfTracked(CheckerContext &C,
  315. const Stmt *AllocDeallocStmt,
  316. bool IsALeakCheck = false) const;
  317. Optional<CheckKind> getCheckIfTracked(CheckerContext &C, SymbolRef Sym,
  318. bool IsALeakCheck = false) const;
  319. ///@}
  320. static bool SummarizeValue(raw_ostream &os, SVal V);
  321. static bool SummarizeRegion(raw_ostream &os, const MemRegion *MR);
  322. void ReportBadFree(CheckerContext &C, SVal ArgVal, SourceRange Range,
  323. const Expr *DeallocExpr) const;
  324. void ReportFreeAlloca(CheckerContext &C, SVal ArgVal,
  325. SourceRange Range) const;
  326. void ReportMismatchedDealloc(CheckerContext &C, SourceRange Range,
  327. const Expr *DeallocExpr, const RefState *RS,
  328. SymbolRef Sym, bool OwnershipTransferred) const;
  329. void ReportOffsetFree(CheckerContext &C, SVal ArgVal, SourceRange Range,
  330. const Expr *DeallocExpr,
  331. const Expr *AllocExpr = nullptr) const;
  332. void ReportUseAfterFree(CheckerContext &C, SourceRange Range,
  333. SymbolRef Sym) const;
  334. void ReportDoubleFree(CheckerContext &C, SourceRange Range, bool Released,
  335. SymbolRef Sym, SymbolRef PrevSym) const;
  336. void ReportDoubleDelete(CheckerContext &C, SymbolRef Sym) const;
  337. void ReportUseZeroAllocated(CheckerContext &C, SourceRange Range,
  338. SymbolRef Sym) const;
  339. /// Find the location of the allocation for Sym on the path leading to the
  340. /// exploded node N.
  341. LeakInfo getAllocationSite(const ExplodedNode *N, SymbolRef Sym,
  342. CheckerContext &C) const;
  343. void reportLeak(SymbolRef Sym, ExplodedNode *N, CheckerContext &C) const;
  344. /// The bug visitor which allows us to print extra diagnostics along the
  345. /// BugReport path. For example, showing the allocation site of the leaked
  346. /// region.
  347. class MallocBugVisitor final
  348. : public BugReporterVisitorImpl<MallocBugVisitor> {
  349. protected:
  350. enum NotificationMode {
  351. Normal,
  352. ReallocationFailed
  353. };
  354. // The allocated region symbol tracked by the main analysis.
  355. SymbolRef Sym;
  356. // The mode we are in, i.e. what kind of diagnostics will be emitted.
  357. NotificationMode Mode;
  358. // A symbol from when the primary region should have been reallocated.
  359. SymbolRef FailedReallocSymbol;
  360. bool IsLeak;
  361. public:
  362. MallocBugVisitor(SymbolRef S, bool isLeak = false)
  363. : Sym(S), Mode(Normal), FailedReallocSymbol(nullptr), IsLeak(isLeak) {}
  364. void Profile(llvm::FoldingSetNodeID &ID) const override {
  365. static int X = 0;
  366. ID.AddPointer(&X);
  367. ID.AddPointer(Sym);
  368. }
  369. inline bool isAllocated(const RefState *S, const RefState *SPrev,
  370. const Stmt *Stmt) {
  371. // Did not track -> allocated. Other state (released) -> allocated.
  372. return (Stmt && (isa<CallExpr>(Stmt) || isa<CXXNewExpr>(Stmt)) &&
  373. (S && (S->isAllocated() || S->isAllocatedOfSizeZero())) &&
  374. (!SPrev || !(SPrev->isAllocated() ||
  375. SPrev->isAllocatedOfSizeZero())));
  376. }
  377. inline bool isReleased(const RefState *S, const RefState *SPrev,
  378. const Stmt *Stmt) {
  379. // Did not track -> released. Other state (allocated) -> released.
  380. return (Stmt && (isa<CallExpr>(Stmt) || isa<CXXDeleteExpr>(Stmt)) &&
  381. (S && S->isReleased()) && (!SPrev || !SPrev->isReleased()));
  382. }
  383. inline bool isRelinquished(const RefState *S, const RefState *SPrev,
  384. const Stmt *Stmt) {
  385. // Did not track -> relinquished. Other state (allocated) -> relinquished.
  386. return (Stmt && (isa<CallExpr>(Stmt) || isa<ObjCMessageExpr>(Stmt) ||
  387. isa<ObjCPropertyRefExpr>(Stmt)) &&
  388. (S && S->isRelinquished()) &&
  389. (!SPrev || !SPrev->isRelinquished()));
  390. }
  391. inline bool isReallocFailedCheck(const RefState *S, const RefState *SPrev,
  392. const Stmt *Stmt) {
  393. // If the expression is not a call, and the state change is
  394. // released -> allocated, it must be the realloc return value
  395. // check. If we have to handle more cases here, it might be cleaner just
  396. // to track this extra bit in the state itself.
  397. return ((!Stmt || !isa<CallExpr>(Stmt)) &&
  398. (S && (S->isAllocated() || S->isAllocatedOfSizeZero())) &&
  399. (SPrev && !(SPrev->isAllocated() ||
  400. SPrev->isAllocatedOfSizeZero())));
  401. }
  402. PathDiagnosticPiece *VisitNode(const ExplodedNode *N,
  403. const ExplodedNode *PrevN,
  404. BugReporterContext &BRC,
  405. BugReport &BR) override;
  406. std::unique_ptr<PathDiagnosticPiece>
  407. getEndPath(BugReporterContext &BRC, const ExplodedNode *EndPathNode,
  408. BugReport &BR) override {
  409. if (!IsLeak)
  410. return nullptr;
  411. PathDiagnosticLocation L =
  412. PathDiagnosticLocation::createEndOfPath(EndPathNode,
  413. BRC.getSourceManager());
  414. // Do not add the statement itself as a range in case of leak.
  415. return llvm::make_unique<PathDiagnosticEventPiece>(L, BR.getDescription(),
  416. false);
  417. }
  418. private:
  419. class StackHintGeneratorForReallocationFailed
  420. : public StackHintGeneratorForSymbol {
  421. public:
  422. StackHintGeneratorForReallocationFailed(SymbolRef S, StringRef M)
  423. : StackHintGeneratorForSymbol(S, M) {}
  424. std::string getMessageForArg(const Expr *ArgE,
  425. unsigned ArgIndex) override {
  426. // Printed parameters start at 1, not 0.
  427. ++ArgIndex;
  428. SmallString<200> buf;
  429. llvm::raw_svector_ostream os(buf);
  430. os << "Reallocation of " << ArgIndex << llvm::getOrdinalSuffix(ArgIndex)
  431. << " parameter failed";
  432. return os.str();
  433. }
  434. std::string getMessageForReturn(const CallExpr *CallExpr) override {
  435. return "Reallocation of returned value failed";
  436. }
  437. };
  438. };
  439. };
  440. } // end anonymous namespace
  441. REGISTER_MAP_WITH_PROGRAMSTATE(RegionState, SymbolRef, RefState)
  442. REGISTER_MAP_WITH_PROGRAMSTATE(ReallocPairs, SymbolRef, ReallocPair)
  443. REGISTER_SET_WITH_PROGRAMSTATE(ReallocSizeZeroSymbols, SymbolRef)
  444. // A map from the freed symbol to the symbol representing the return value of
  445. // the free function.
  446. REGISTER_MAP_WITH_PROGRAMSTATE(FreeReturnValue, SymbolRef, SymbolRef)
  447. namespace {
  448. class StopTrackingCallback final : public SymbolVisitor {
  449. ProgramStateRef state;
  450. public:
  451. StopTrackingCallback(ProgramStateRef st) : state(st) {}
  452. ProgramStateRef getState() const { return state; }
  453. bool VisitSymbol(SymbolRef sym) override {
  454. state = state->remove<RegionState>(sym);
  455. return true;
  456. }
  457. };
  458. } // end anonymous namespace
  459. void MallocChecker::initIdentifierInfo(ASTContext &Ctx) const {
  460. if (II_malloc)
  461. return;
  462. II_alloca = &Ctx.Idents.get("alloca");
  463. II_malloc = &Ctx.Idents.get("malloc");
  464. II_free = &Ctx.Idents.get("free");
  465. II_realloc = &Ctx.Idents.get("realloc");
  466. II_reallocf = &Ctx.Idents.get("reallocf");
  467. II_calloc = &Ctx.Idents.get("calloc");
  468. II_valloc = &Ctx.Idents.get("valloc");
  469. II_strdup = &Ctx.Idents.get("strdup");
  470. II_strndup = &Ctx.Idents.get("strndup");
  471. II_kmalloc = &Ctx.Idents.get("kmalloc");
  472. II_if_nameindex = &Ctx.Idents.get("if_nameindex");
  473. II_if_freenameindex = &Ctx.Idents.get("if_freenameindex");
  474. }
  475. bool MallocChecker::isMemFunction(const FunctionDecl *FD, ASTContext &C) const {
  476. if (isCMemFunction(FD, C, AF_Malloc, MemoryOperationKind::MOK_Any))
  477. return true;
  478. if (isCMemFunction(FD, C, AF_IfNameIndex, MemoryOperationKind::MOK_Any))
  479. return true;
  480. if (isCMemFunction(FD, C, AF_Alloca, MemoryOperationKind::MOK_Any))
  481. return true;
  482. if (isStandardNewDelete(FD, C))
  483. return true;
  484. return false;
  485. }
  486. bool MallocChecker::isCMemFunction(const FunctionDecl *FD,
  487. ASTContext &C,
  488. AllocationFamily Family,
  489. MemoryOperationKind MemKind) const {
  490. if (!FD)
  491. return false;
  492. bool CheckFree = (MemKind == MemoryOperationKind::MOK_Any ||
  493. MemKind == MemoryOperationKind::MOK_Free);
  494. bool CheckAlloc = (MemKind == MemoryOperationKind::MOK_Any ||
  495. MemKind == MemoryOperationKind::MOK_Allocate);
  496. if (FD->getKind() == Decl::Function) {
  497. const IdentifierInfo *FunI = FD->getIdentifier();
  498. initIdentifierInfo(C);
  499. if (Family == AF_Malloc && CheckFree) {
  500. if (FunI == II_free || FunI == II_realloc || FunI == II_reallocf)
  501. return true;
  502. }
  503. if (Family == AF_Malloc && CheckAlloc) {
  504. if (FunI == II_malloc || FunI == II_realloc || FunI == II_reallocf ||
  505. FunI == II_calloc || FunI == II_valloc || FunI == II_strdup ||
  506. FunI == II_strndup || FunI == II_kmalloc)
  507. return true;
  508. }
  509. if (Family == AF_IfNameIndex && CheckFree) {
  510. if (FunI == II_if_freenameindex)
  511. return true;
  512. }
  513. if (Family == AF_IfNameIndex && CheckAlloc) {
  514. if (FunI == II_if_nameindex)
  515. return true;
  516. }
  517. if (Family == AF_Alloca && CheckAlloc) {
  518. if (FunI == II_alloca)
  519. return true;
  520. }
  521. }
  522. if (Family != AF_Malloc)
  523. return false;
  524. if (IsOptimistic && FD->hasAttrs()) {
  525. for (const auto *I : FD->specific_attrs<OwnershipAttr>()) {
  526. OwnershipAttr::OwnershipKind OwnKind = I->getOwnKind();
  527. if(OwnKind == OwnershipAttr::Takes || OwnKind == OwnershipAttr::Holds) {
  528. if (CheckFree)
  529. return true;
  530. } else if (OwnKind == OwnershipAttr::Returns) {
  531. if (CheckAlloc)
  532. return true;
  533. }
  534. }
  535. }
  536. return false;
  537. }
  538. // Tells if the callee is one of the following:
  539. // 1) A global non-placement new/delete operator function.
  540. // 2) A global placement operator function with the single placement argument
  541. // of type std::nothrow_t.
  542. bool MallocChecker::isStandardNewDelete(const FunctionDecl *FD,
  543. ASTContext &C) const {
  544. if (!FD)
  545. return false;
  546. OverloadedOperatorKind Kind = FD->getOverloadedOperator();
  547. if (Kind != OO_New && Kind != OO_Array_New &&
  548. Kind != OO_Delete && Kind != OO_Array_Delete)
  549. return false;
  550. // Skip all operator new/delete methods.
  551. if (isa<CXXMethodDecl>(FD))
  552. return false;
  553. // Return true if tested operator is a standard placement nothrow operator.
  554. if (FD->getNumParams() == 2) {
  555. QualType T = FD->getParamDecl(1)->getType();
  556. if (const IdentifierInfo *II = T.getBaseTypeIdentifier())
  557. return II->getName().equals("nothrow_t");
  558. }
  559. // Skip placement operators.
  560. if (FD->getNumParams() != 1 || FD->isVariadic())
  561. return false;
  562. // One of the standard new/new[]/delete/delete[] non-placement operators.
  563. return true;
  564. }
  565. llvm::Optional<ProgramStateRef> MallocChecker::performKernelMalloc(
  566. const CallExpr *CE, CheckerContext &C, const ProgramStateRef &State) const {
  567. // 3-argument malloc(), as commonly used in {Free,Net,Open}BSD Kernels:
  568. //
  569. // void *malloc(unsigned long size, struct malloc_type *mtp, int flags);
  570. //
  571. // One of the possible flags is M_ZERO, which means 'give me back an
  572. // allocation which is already zeroed', like calloc.
  573. // 2-argument kmalloc(), as used in the Linux kernel:
  574. //
  575. // void *kmalloc(size_t size, gfp_t flags);
  576. //
  577. // Has the similar flag value __GFP_ZERO.
  578. // This logic is largely cloned from O_CREAT in UnixAPIChecker, maybe some
  579. // code could be shared.
  580. ASTContext &Ctx = C.getASTContext();
  581. llvm::Triple::OSType OS = Ctx.getTargetInfo().getTriple().getOS();
  582. if (!KernelZeroFlagVal.hasValue()) {
  583. if (OS == llvm::Triple::FreeBSD)
  584. KernelZeroFlagVal = 0x0100;
  585. else if (OS == llvm::Triple::NetBSD)
  586. KernelZeroFlagVal = 0x0002;
  587. else if (OS == llvm::Triple::OpenBSD)
  588. KernelZeroFlagVal = 0x0008;
  589. else if (OS == llvm::Triple::Linux)
  590. // __GFP_ZERO
  591. KernelZeroFlagVal = 0x8000;
  592. else
  593. // FIXME: We need a more general way of getting the M_ZERO value.
  594. // See also: O_CREAT in UnixAPIChecker.cpp.
  595. // Fall back to normal malloc behavior on platforms where we don't
  596. // know M_ZERO.
  597. return None;
  598. }
  599. // We treat the last argument as the flags argument, and callers fall-back to
  600. // normal malloc on a None return. This works for the FreeBSD kernel malloc
  601. // as well as Linux kmalloc.
  602. if (CE->getNumArgs() < 2)
  603. return None;
  604. const Expr *FlagsEx = CE->getArg(CE->getNumArgs() - 1);
  605. const SVal V = State->getSVal(FlagsEx, C.getLocationContext());
  606. if (!V.getAs<NonLoc>()) {
  607. // The case where 'V' can be a location can only be due to a bad header,
  608. // so in this case bail out.
  609. return None;
  610. }
  611. NonLoc Flags = V.castAs<NonLoc>();
  612. NonLoc ZeroFlag = C.getSValBuilder()
  613. .makeIntVal(KernelZeroFlagVal.getValue(), FlagsEx->getType())
  614. .castAs<NonLoc>();
  615. SVal MaskedFlagsUC = C.getSValBuilder().evalBinOpNN(State, BO_And,
  616. Flags, ZeroFlag,
  617. FlagsEx->getType());
  618. if (MaskedFlagsUC.isUnknownOrUndef())
  619. return None;
  620. DefinedSVal MaskedFlags = MaskedFlagsUC.castAs<DefinedSVal>();
  621. // Check if maskedFlags is non-zero.
  622. ProgramStateRef TrueState, FalseState;
  623. std::tie(TrueState, FalseState) = State->assume(MaskedFlags);
  624. // If M_ZERO is set, treat this like calloc (initialized).
  625. if (TrueState && !FalseState) {
  626. SVal ZeroVal = C.getSValBuilder().makeZeroVal(Ctx.CharTy);
  627. return MallocMemAux(C, CE, CE->getArg(0), ZeroVal, TrueState);
  628. }
  629. return None;
  630. }
  631. void MallocChecker::checkPostStmt(const CallExpr *CE, CheckerContext &C) const {
  632. if (C.wasInlined)
  633. return;
  634. const FunctionDecl *FD = C.getCalleeDecl(CE);
  635. if (!FD)
  636. return;
  637. ProgramStateRef State = C.getState();
  638. bool ReleasedAllocatedMemory = false;
  639. if (FD->getKind() == Decl::Function) {
  640. initIdentifierInfo(C.getASTContext());
  641. IdentifierInfo *FunI = FD->getIdentifier();
  642. if (FunI == II_malloc) {
  643. if (CE->getNumArgs() < 1)
  644. return;
  645. if (CE->getNumArgs() < 3) {
  646. State = MallocMemAux(C, CE, CE->getArg(0), UndefinedVal(), State);
  647. if (CE->getNumArgs() == 1)
  648. State = ProcessZeroAllocation(C, CE, 0, State);
  649. } else if (CE->getNumArgs() == 3) {
  650. llvm::Optional<ProgramStateRef> MaybeState =
  651. performKernelMalloc(CE, C, State);
  652. if (MaybeState.hasValue())
  653. State = MaybeState.getValue();
  654. else
  655. State = MallocMemAux(C, CE, CE->getArg(0), UndefinedVal(), State);
  656. }
  657. } else if (FunI == II_kmalloc) {
  658. llvm::Optional<ProgramStateRef> MaybeState =
  659. performKernelMalloc(CE, C, State);
  660. if (MaybeState.hasValue())
  661. State = MaybeState.getValue();
  662. else
  663. State = MallocMemAux(C, CE, CE->getArg(0), UndefinedVal(), State);
  664. } else if (FunI == II_valloc) {
  665. if (CE->getNumArgs() < 1)
  666. return;
  667. State = MallocMemAux(C, CE, CE->getArg(0), UndefinedVal(), State);
  668. State = ProcessZeroAllocation(C, CE, 0, State);
  669. } else if (FunI == II_realloc) {
  670. State = ReallocMem(C, CE, false, State);
  671. State = ProcessZeroAllocation(C, CE, 1, State);
  672. } else if (FunI == II_reallocf) {
  673. State = ReallocMem(C, CE, true, State);
  674. State = ProcessZeroAllocation(C, CE, 1, State);
  675. } else if (FunI == II_calloc) {
  676. State = CallocMem(C, CE, State);
  677. State = ProcessZeroAllocation(C, CE, 0, State);
  678. State = ProcessZeroAllocation(C, CE, 1, State);
  679. } else if (FunI == II_free) {
  680. State = FreeMemAux(C, CE, State, 0, false, ReleasedAllocatedMemory);
  681. } else if (FunI == II_strdup) {
  682. State = MallocUpdateRefState(C, CE, State);
  683. } else if (FunI == II_strndup) {
  684. State = MallocUpdateRefState(C, CE, State);
  685. } else if (FunI == II_alloca) {
  686. State = MallocMemAux(C, CE, CE->getArg(0), UndefinedVal(), State,
  687. AF_Alloca);
  688. State = ProcessZeroAllocation(C, CE, 0, State);
  689. } else if (isStandardNewDelete(FD, C.getASTContext())) {
  690. // Process direct calls to operator new/new[]/delete/delete[] functions
  691. // as distinct from new/new[]/delete/delete[] expressions that are
  692. // processed by the checkPostStmt callbacks for CXXNewExpr and
  693. // CXXDeleteExpr.
  694. OverloadedOperatorKind K = FD->getOverloadedOperator();
  695. if (K == OO_New) {
  696. State = MallocMemAux(C, CE, CE->getArg(0), UndefinedVal(), State,
  697. AF_CXXNew);
  698. State = ProcessZeroAllocation(C, CE, 0, State);
  699. }
  700. else if (K == OO_Array_New) {
  701. State = MallocMemAux(C, CE, CE->getArg(0), UndefinedVal(), State,
  702. AF_CXXNewArray);
  703. State = ProcessZeroAllocation(C, CE, 0, State);
  704. }
  705. else if (K == OO_Delete || K == OO_Array_Delete)
  706. State = FreeMemAux(C, CE, State, 0, false, ReleasedAllocatedMemory);
  707. else
  708. llvm_unreachable("not a new/delete operator");
  709. } else if (FunI == II_if_nameindex) {
  710. // Should we model this differently? We can allocate a fixed number of
  711. // elements with zeros in the last one.
  712. State = MallocMemAux(C, CE, UnknownVal(), UnknownVal(), State,
  713. AF_IfNameIndex);
  714. } else if (FunI == II_if_freenameindex) {
  715. State = FreeMemAux(C, CE, State, 0, false, ReleasedAllocatedMemory);
  716. }
  717. }
  718. if (IsOptimistic || ChecksEnabled[CK_MismatchedDeallocatorChecker]) {
  719. // Check all the attributes, if there are any.
  720. // There can be multiple of these attributes.
  721. if (FD->hasAttrs())
  722. for (const auto *I : FD->specific_attrs<OwnershipAttr>()) {
  723. switch (I->getOwnKind()) {
  724. case OwnershipAttr::Returns:
  725. State = MallocMemReturnsAttr(C, CE, I, State);
  726. break;
  727. case OwnershipAttr::Takes:
  728. case OwnershipAttr::Holds:
  729. State = FreeMemAttr(C, CE, I, State);
  730. break;
  731. }
  732. }
  733. }
  734. C.addTransition(State);
  735. }
  736. // Performs a 0-sized allocations check.
  737. ProgramStateRef MallocChecker::ProcessZeroAllocation(CheckerContext &C,
  738. const Expr *E,
  739. const unsigned AllocationSizeArg,
  740. ProgramStateRef State) const {
  741. if (!State)
  742. return nullptr;
  743. const Expr *Arg = nullptr;
  744. if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
  745. Arg = CE->getArg(AllocationSizeArg);
  746. }
  747. else if (const CXXNewExpr *NE = dyn_cast<CXXNewExpr>(E)) {
  748. if (NE->isArray())
  749. Arg = NE->getArraySize();
  750. else
  751. return State;
  752. }
  753. else
  754. llvm_unreachable("not a CallExpr or CXXNewExpr");
  755. assert(Arg);
  756. Optional<DefinedSVal> DefArgVal =
  757. State->getSVal(Arg, C.getLocationContext()).getAs<DefinedSVal>();
  758. if (!DefArgVal)
  759. return State;
  760. // Check if the allocation size is 0.
  761. ProgramStateRef TrueState, FalseState;
  762. SValBuilder &SvalBuilder = C.getSValBuilder();
  763. DefinedSVal Zero =
  764. SvalBuilder.makeZeroVal(Arg->getType()).castAs<DefinedSVal>();
  765. std::tie(TrueState, FalseState) =
  766. State->assume(SvalBuilder.evalEQ(State, *DefArgVal, Zero));
  767. if (TrueState && !FalseState) {
  768. SVal retVal = State->getSVal(E, C.getLocationContext());
  769. SymbolRef Sym = retVal.getAsLocSymbol();
  770. if (!Sym)
  771. return State;
  772. const RefState *RS = State->get<RegionState>(Sym);
  773. if (RS) {
  774. if (RS->isAllocated())
  775. return TrueState->set<RegionState>(Sym,
  776. RefState::getAllocatedOfSizeZero(RS));
  777. else
  778. return State;
  779. } else {
  780. // Case of zero-size realloc. Historically 'realloc(ptr, 0)' is treated as
  781. // 'free(ptr)' and the returned value from 'realloc(ptr, 0)' is not
  782. // tracked. Add zero-reallocated Sym to the state to catch references
  783. // to zero-allocated memory.
  784. return TrueState->add<ReallocSizeZeroSymbols>(Sym);
  785. }
  786. }
  787. // Assume the value is non-zero going forward.
  788. assert(FalseState);
  789. return FalseState;
  790. }
  791. static QualType getDeepPointeeType(QualType T) {
  792. QualType Result = T, PointeeType = T->getPointeeType();
  793. while (!PointeeType.isNull()) {
  794. Result = PointeeType;
  795. PointeeType = PointeeType->getPointeeType();
  796. }
  797. return Result;
  798. }
  799. static bool treatUnusedNewEscaped(const CXXNewExpr *NE) {
  800. const CXXConstructExpr *ConstructE = NE->getConstructExpr();
  801. if (!ConstructE)
  802. return false;
  803. if (!NE->getAllocatedType()->getAsCXXRecordDecl())
  804. return false;
  805. const CXXConstructorDecl *CtorD = ConstructE->getConstructor();
  806. // Iterate over the constructor parameters.
  807. for (const auto *CtorParam : CtorD->params()) {
  808. QualType CtorParamPointeeT = CtorParam->getType()->getPointeeType();
  809. if (CtorParamPointeeT.isNull())
  810. continue;
  811. CtorParamPointeeT = getDeepPointeeType(CtorParamPointeeT);
  812. if (CtorParamPointeeT->getAsCXXRecordDecl())
  813. return true;
  814. }
  815. return false;
  816. }
  817. void MallocChecker::checkPostStmt(const CXXNewExpr *NE,
  818. CheckerContext &C) const {
  819. if (NE->getNumPlacementArgs())
  820. for (CXXNewExpr::const_arg_iterator I = NE->placement_arg_begin(),
  821. E = NE->placement_arg_end(); I != E; ++I)
  822. if (SymbolRef Sym = C.getSVal(*I).getAsSymbol())
  823. checkUseAfterFree(Sym, C, *I);
  824. if (!isStandardNewDelete(NE->getOperatorNew(), C.getASTContext()))
  825. return;
  826. ParentMap &PM = C.getLocationContext()->getParentMap();
  827. if (!PM.isConsumedExpr(NE) && treatUnusedNewEscaped(NE))
  828. return;
  829. ProgramStateRef State = C.getState();
  830. // The return value from operator new is bound to a specified initialization
  831. // value (if any) and we don't want to loose this value. So we call
  832. // MallocUpdateRefState() instead of MallocMemAux() which breakes the
  833. // existing binding.
  834. State = MallocUpdateRefState(C, NE, State, NE->isArray() ? AF_CXXNewArray
  835. : AF_CXXNew);
  836. State = ProcessZeroAllocation(C, NE, 0, State);
  837. C.addTransition(State);
  838. }
  839. void MallocChecker::checkPreStmt(const CXXDeleteExpr *DE,
  840. CheckerContext &C) const {
  841. if (!ChecksEnabled[CK_NewDeleteChecker])
  842. if (SymbolRef Sym = C.getSVal(DE->getArgument()).getAsSymbol())
  843. checkUseAfterFree(Sym, C, DE->getArgument());
  844. if (!isStandardNewDelete(DE->getOperatorDelete(), C.getASTContext()))
  845. return;
  846. ProgramStateRef State = C.getState();
  847. bool ReleasedAllocated;
  848. State = FreeMemAux(C, DE->getArgument(), DE, State,
  849. /*Hold*/false, ReleasedAllocated);
  850. C.addTransition(State);
  851. }
  852. static bool isKnownDeallocObjCMethodName(const ObjCMethodCall &Call) {
  853. // If the first selector piece is one of the names below, assume that the
  854. // object takes ownership of the memory, promising to eventually deallocate it
  855. // with free().
  856. // Ex: [NSData dataWithBytesNoCopy:bytes length:10];
  857. // (...unless a 'freeWhenDone' parameter is false, but that's checked later.)
  858. StringRef FirstSlot = Call.getSelector().getNameForSlot(0);
  859. return FirstSlot == "dataWithBytesNoCopy" ||
  860. FirstSlot == "initWithBytesNoCopy" ||
  861. FirstSlot == "initWithCharactersNoCopy";
  862. }
  863. static Optional<bool> getFreeWhenDoneArg(const ObjCMethodCall &Call) {
  864. Selector S = Call.getSelector();
  865. // FIXME: We should not rely on fully-constrained symbols being folded.
  866. for (unsigned i = 1; i < S.getNumArgs(); ++i)
  867. if (S.getNameForSlot(i).equals("freeWhenDone"))
  868. return !Call.getArgSVal(i).isZeroConstant();
  869. return None;
  870. }
  871. void MallocChecker::checkPostObjCMessage(const ObjCMethodCall &Call,
  872. CheckerContext &C) const {
  873. if (C.wasInlined)
  874. return;
  875. if (!isKnownDeallocObjCMethodName(Call))
  876. return;
  877. if (Optional<bool> FreeWhenDone = getFreeWhenDoneArg(Call))
  878. if (!*FreeWhenDone)
  879. return;
  880. bool ReleasedAllocatedMemory;
  881. ProgramStateRef State = FreeMemAux(C, Call.getArgExpr(0),
  882. Call.getOriginExpr(), C.getState(),
  883. /*Hold=*/true, ReleasedAllocatedMemory,
  884. /*RetNullOnFailure=*/true);
  885. C.addTransition(State);
  886. }
  887. ProgramStateRef
  888. MallocChecker::MallocMemReturnsAttr(CheckerContext &C, const CallExpr *CE,
  889. const OwnershipAttr *Att,
  890. ProgramStateRef State) const {
  891. if (!State)
  892. return nullptr;
  893. if (Att->getModule() != II_malloc)
  894. return nullptr;
  895. OwnershipAttr::args_iterator I = Att->args_begin(), E = Att->args_end();
  896. if (I != E) {
  897. return MallocMemAux(C, CE, CE->getArg(*I), UndefinedVal(), State);
  898. }
  899. return MallocMemAux(C, CE, UnknownVal(), UndefinedVal(), State);
  900. }
  901. ProgramStateRef MallocChecker::MallocMemAux(CheckerContext &C,
  902. const CallExpr *CE,
  903. const Expr *SizeEx, SVal Init,
  904. ProgramStateRef State,
  905. AllocationFamily Family) {
  906. if (!State)
  907. return nullptr;
  908. return MallocMemAux(C, CE, State->getSVal(SizeEx, C.getLocationContext()),
  909. Init, State, Family);
  910. }
  911. ProgramStateRef MallocChecker::MallocMemAux(CheckerContext &C,
  912. const CallExpr *CE,
  913. SVal Size, SVal Init,
  914. ProgramStateRef State,
  915. AllocationFamily Family) {
  916. if (!State)
  917. return nullptr;
  918. // We expect the malloc functions to return a pointer.
  919. if (!Loc::isLocType(CE->getType()))
  920. return nullptr;
  921. // Bind the return value to the symbolic value from the heap region.
  922. // TODO: We could rewrite post visit to eval call; 'malloc' does not have
  923. // side effects other than what we model here.
  924. unsigned Count = C.blockCount();
  925. SValBuilder &svalBuilder = C.getSValBuilder();
  926. const LocationContext *LCtx = C.getPredecessor()->getLocationContext();
  927. DefinedSVal RetVal = svalBuilder.getConjuredHeapSymbolVal(CE, LCtx, Count)
  928. .castAs<DefinedSVal>();
  929. State = State->BindExpr(CE, C.getLocationContext(), RetVal);
  930. // Fill the region with the initialization value.
  931. State = State->bindDefault(RetVal, Init);
  932. // Set the region's extent equal to the Size parameter.
  933. const SymbolicRegion *R =
  934. dyn_cast_or_null<SymbolicRegion>(RetVal.getAsRegion());
  935. if (!R)
  936. return nullptr;
  937. if (Optional<DefinedOrUnknownSVal> DefinedSize =
  938. Size.getAs<DefinedOrUnknownSVal>()) {
  939. SValBuilder &svalBuilder = C.getSValBuilder();
  940. DefinedOrUnknownSVal Extent = R->getExtent(svalBuilder);
  941. DefinedOrUnknownSVal extentMatchesSize =
  942. svalBuilder.evalEQ(State, Extent, *DefinedSize);
  943. State = State->assume(extentMatchesSize, true);
  944. assert(State);
  945. }
  946. return MallocUpdateRefState(C, CE, State, Family);
  947. }
  948. ProgramStateRef MallocChecker::MallocUpdateRefState(CheckerContext &C,
  949. const Expr *E,
  950. ProgramStateRef State,
  951. AllocationFamily Family) {
  952. if (!State)
  953. return nullptr;
  954. // Get the return value.
  955. SVal retVal = State->getSVal(E, C.getLocationContext());
  956. // We expect the malloc functions to return a pointer.
  957. if (!retVal.getAs<Loc>())
  958. return nullptr;
  959. SymbolRef Sym = retVal.getAsLocSymbol();
  960. assert(Sym);
  961. // Set the symbol's state to Allocated.
  962. return State->set<RegionState>(Sym, RefState::getAllocated(Family, E));
  963. }
  964. ProgramStateRef MallocChecker::FreeMemAttr(CheckerContext &C,
  965. const CallExpr *CE,
  966. const OwnershipAttr *Att,
  967. ProgramStateRef State) const {
  968. if (!State)
  969. return nullptr;
  970. if (Att->getModule() != II_malloc)
  971. return nullptr;
  972. bool ReleasedAllocated = false;
  973. for (const auto &Arg : Att->args()) {
  974. ProgramStateRef StateI = FreeMemAux(C, CE, State, Arg,
  975. Att->getOwnKind() == OwnershipAttr::Holds,
  976. ReleasedAllocated);
  977. if (StateI)
  978. State = StateI;
  979. }
  980. return State;
  981. }
  982. ProgramStateRef MallocChecker::FreeMemAux(CheckerContext &C,
  983. const CallExpr *CE,
  984. ProgramStateRef State,
  985. unsigned Num,
  986. bool Hold,
  987. bool &ReleasedAllocated,
  988. bool ReturnsNullOnFailure) const {
  989. if (!State)
  990. return nullptr;
  991. if (CE->getNumArgs() < (Num + 1))
  992. return nullptr;
  993. return FreeMemAux(C, CE->getArg(Num), CE, State, Hold,
  994. ReleasedAllocated, ReturnsNullOnFailure);
  995. }
  996. /// Checks if the previous call to free on the given symbol failed - if free
  997. /// failed, returns true. Also, returns the corresponding return value symbol.
  998. static bool didPreviousFreeFail(ProgramStateRef State,
  999. SymbolRef Sym, SymbolRef &RetStatusSymbol) {
  1000. const SymbolRef *Ret = State->get<FreeReturnValue>(Sym);
  1001. if (Ret) {
  1002. assert(*Ret && "We should not store the null return symbol");
  1003. ConstraintManager &CMgr = State->getConstraintManager();
  1004. ConditionTruthVal FreeFailed = CMgr.isNull(State, *Ret);
  1005. RetStatusSymbol = *Ret;
  1006. return FreeFailed.isConstrainedTrue();
  1007. }
  1008. return false;
  1009. }
  1010. AllocationFamily MallocChecker::getAllocationFamily(CheckerContext &C,
  1011. const Stmt *S) const {
  1012. if (!S)
  1013. return AF_None;
  1014. if (const CallExpr *CE = dyn_cast<CallExpr>(S)) {
  1015. const FunctionDecl *FD = C.getCalleeDecl(CE);
  1016. if (!FD)
  1017. FD = dyn_cast<FunctionDecl>(CE->getCalleeDecl());
  1018. ASTContext &Ctx = C.getASTContext();
  1019. if (isCMemFunction(FD, Ctx, AF_Malloc, MemoryOperationKind::MOK_Any))
  1020. return AF_Malloc;
  1021. if (isStandardNewDelete(FD, Ctx)) {
  1022. OverloadedOperatorKind Kind = FD->getOverloadedOperator();
  1023. if (Kind == OO_New || Kind == OO_Delete)
  1024. return AF_CXXNew;
  1025. else if (Kind == OO_Array_New || Kind == OO_Array_Delete)
  1026. return AF_CXXNewArray;
  1027. }
  1028. if (isCMemFunction(FD, Ctx, AF_IfNameIndex, MemoryOperationKind::MOK_Any))
  1029. return AF_IfNameIndex;
  1030. if (isCMemFunction(FD, Ctx, AF_Alloca, MemoryOperationKind::MOK_Any))
  1031. return AF_Alloca;
  1032. return AF_None;
  1033. }
  1034. if (const CXXNewExpr *NE = dyn_cast<CXXNewExpr>(S))
  1035. return NE->isArray() ? AF_CXXNewArray : AF_CXXNew;
  1036. if (const CXXDeleteExpr *DE = dyn_cast<CXXDeleteExpr>(S))
  1037. return DE->isArrayForm() ? AF_CXXNewArray : AF_CXXNew;
  1038. if (isa<ObjCMessageExpr>(S))
  1039. return AF_Malloc;
  1040. return AF_None;
  1041. }
  1042. bool MallocChecker::printAllocDeallocName(raw_ostream &os, CheckerContext &C,
  1043. const Expr *E) const {
  1044. if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
  1045. // FIXME: This doesn't handle indirect calls.
  1046. const FunctionDecl *FD = CE->getDirectCallee();
  1047. if (!FD)
  1048. return false;
  1049. os << *FD;
  1050. if (!FD->isOverloadedOperator())
  1051. os << "()";
  1052. return true;
  1053. }
  1054. if (const ObjCMessageExpr *Msg = dyn_cast<ObjCMessageExpr>(E)) {
  1055. if (Msg->isInstanceMessage())
  1056. os << "-";
  1057. else
  1058. os << "+";
  1059. Msg->getSelector().print(os);
  1060. return true;
  1061. }
  1062. if (const CXXNewExpr *NE = dyn_cast<CXXNewExpr>(E)) {
  1063. os << "'"
  1064. << getOperatorSpelling(NE->getOperatorNew()->getOverloadedOperator())
  1065. << "'";
  1066. return true;
  1067. }
  1068. if (const CXXDeleteExpr *DE = dyn_cast<CXXDeleteExpr>(E)) {
  1069. os << "'"
  1070. << getOperatorSpelling(DE->getOperatorDelete()->getOverloadedOperator())
  1071. << "'";
  1072. return true;
  1073. }
  1074. return false;
  1075. }
  1076. void MallocChecker::printExpectedAllocName(raw_ostream &os, CheckerContext &C,
  1077. const Expr *E) const {
  1078. AllocationFamily Family = getAllocationFamily(C, E);
  1079. switch(Family) {
  1080. case AF_Malloc: os << "malloc()"; return;
  1081. case AF_CXXNew: os << "'new'"; return;
  1082. case AF_CXXNewArray: os << "'new[]'"; return;
  1083. case AF_IfNameIndex: os << "'if_nameindex()'"; return;
  1084. case AF_Alloca:
  1085. case AF_None: llvm_unreachable("not a deallocation expression");
  1086. }
  1087. }
  1088. void MallocChecker::printExpectedDeallocName(raw_ostream &os,
  1089. AllocationFamily Family) const {
  1090. switch(Family) {
  1091. case AF_Malloc: os << "free()"; return;
  1092. case AF_CXXNew: os << "'delete'"; return;
  1093. case AF_CXXNewArray: os << "'delete[]'"; return;
  1094. case AF_IfNameIndex: os << "'if_freenameindex()'"; return;
  1095. case AF_Alloca:
  1096. case AF_None: llvm_unreachable("suspicious argument");
  1097. }
  1098. }
  1099. ProgramStateRef MallocChecker::FreeMemAux(CheckerContext &C,
  1100. const Expr *ArgExpr,
  1101. const Expr *ParentExpr,
  1102. ProgramStateRef State,
  1103. bool Hold,
  1104. bool &ReleasedAllocated,
  1105. bool ReturnsNullOnFailure) const {
  1106. if (!State)
  1107. return nullptr;
  1108. SVal ArgVal = State->getSVal(ArgExpr, C.getLocationContext());
  1109. if (!ArgVal.getAs<DefinedOrUnknownSVal>())
  1110. return nullptr;
  1111. DefinedOrUnknownSVal location = ArgVal.castAs<DefinedOrUnknownSVal>();
  1112. // Check for null dereferences.
  1113. if (!location.getAs<Loc>())
  1114. return nullptr;
  1115. // The explicit NULL case, no operation is performed.
  1116. ProgramStateRef notNullState, nullState;
  1117. std::tie(notNullState, nullState) = State->assume(location);
  1118. if (nullState && !notNullState)
  1119. return nullptr;
  1120. // Unknown values could easily be okay
  1121. // Undefined values are handled elsewhere
  1122. if (ArgVal.isUnknownOrUndef())
  1123. return nullptr;
  1124. const MemRegion *R = ArgVal.getAsRegion();
  1125. // Nonlocs can't be freed, of course.
  1126. // Non-region locations (labels and fixed addresses) also shouldn't be freed.
  1127. if (!R) {
  1128. ReportBadFree(C, ArgVal, ArgExpr->getSourceRange(), ParentExpr);
  1129. return nullptr;
  1130. }
  1131. R = R->StripCasts();
  1132. // Blocks might show up as heap data, but should not be free()d
  1133. if (isa<BlockDataRegion>(R)) {
  1134. ReportBadFree(C, ArgVal, ArgExpr->getSourceRange(), ParentExpr);
  1135. return nullptr;
  1136. }
  1137. const MemSpaceRegion *MS = R->getMemorySpace();
  1138. // Parameters, locals, statics, globals, and memory returned by
  1139. // __builtin_alloca() shouldn't be freed.
  1140. if (!(isa<UnknownSpaceRegion>(MS) || isa<HeapSpaceRegion>(MS))) {
  1141. // FIXME: at the time this code was written, malloc() regions were
  1142. // represented by conjured symbols, which are all in UnknownSpaceRegion.
  1143. // This means that there isn't actually anything from HeapSpaceRegion
  1144. // that should be freed, even though we allow it here.
  1145. // Of course, free() can work on memory allocated outside the current
  1146. // function, so UnknownSpaceRegion is always a possibility.
  1147. // False negatives are better than false positives.
  1148. if (isa<AllocaRegion>(R))
  1149. ReportFreeAlloca(C, ArgVal, ArgExpr->getSourceRange());
  1150. else
  1151. ReportBadFree(C, ArgVal, ArgExpr->getSourceRange(), ParentExpr);
  1152. return nullptr;
  1153. }
  1154. const SymbolicRegion *SrBase = dyn_cast<SymbolicRegion>(R->getBaseRegion());
  1155. // Various cases could lead to non-symbol values here.
  1156. // For now, ignore them.
  1157. if (!SrBase)
  1158. return nullptr;
  1159. SymbolRef SymBase = SrBase->getSymbol();
  1160. const RefState *RsBase = State->get<RegionState>(SymBase);
  1161. SymbolRef PreviousRetStatusSymbol = nullptr;
  1162. if (RsBase) {
  1163. // Memory returned by alloca() shouldn't be freed.
  1164. if (RsBase->getAllocationFamily() == AF_Alloca) {
  1165. ReportFreeAlloca(C, ArgVal, ArgExpr->getSourceRange());
  1166. return nullptr;
  1167. }
  1168. // Check for double free first.
  1169. if ((RsBase->isReleased() || RsBase->isRelinquished()) &&
  1170. !didPreviousFreeFail(State, SymBase, PreviousRetStatusSymbol)) {
  1171. ReportDoubleFree(C, ParentExpr->getSourceRange(), RsBase->isReleased(),
  1172. SymBase, PreviousRetStatusSymbol);
  1173. return nullptr;
  1174. // If the pointer is allocated or escaped, but we are now trying to free it,
  1175. // check that the call to free is proper.
  1176. } else if (RsBase->isAllocated() || RsBase->isAllocatedOfSizeZero() ||
  1177. RsBase->isEscaped()) {
  1178. // Check if an expected deallocation function matches the real one.
  1179. bool DeallocMatchesAlloc =
  1180. RsBase->getAllocationFamily() == getAllocationFamily(C, ParentExpr);
  1181. if (!DeallocMatchesAlloc) {
  1182. ReportMismatchedDealloc(C, ArgExpr->getSourceRange(),
  1183. ParentExpr, RsBase, SymBase, Hold);
  1184. return nullptr;
  1185. }
  1186. // Check if the memory location being freed is the actual location
  1187. // allocated, or an offset.
  1188. RegionOffset Offset = R->getAsOffset();
  1189. if (Offset.isValid() &&
  1190. !Offset.hasSymbolicOffset() &&
  1191. Offset.getOffset() != 0) {
  1192. const Expr *AllocExpr = cast<Expr>(RsBase->getStmt());
  1193. ReportOffsetFree(C, ArgVal, ArgExpr->getSourceRange(), ParentExpr,
  1194. AllocExpr);
  1195. return nullptr;
  1196. }
  1197. }
  1198. }
  1199. ReleasedAllocated = (RsBase != nullptr) && (RsBase->isAllocated() ||
  1200. RsBase->isAllocatedOfSizeZero());
  1201. // Clean out the info on previous call to free return info.
  1202. State = State->remove<FreeReturnValue>(SymBase);
  1203. // Keep track of the return value. If it is NULL, we will know that free
  1204. // failed.
  1205. if (ReturnsNullOnFailure) {
  1206. SVal RetVal = C.getSVal(ParentExpr);
  1207. SymbolRef RetStatusSymbol = RetVal.getAsSymbol();
  1208. if (RetStatusSymbol) {
  1209. C.getSymbolManager().addSymbolDependency(SymBase, RetStatusSymbol);
  1210. State = State->set<FreeReturnValue>(SymBase, RetStatusSymbol);
  1211. }
  1212. }
  1213. AllocationFamily Family = RsBase ? RsBase->getAllocationFamily()
  1214. : getAllocationFamily(C, ParentExpr);
  1215. // Normal free.
  1216. if (Hold)
  1217. return State->set<RegionState>(SymBase,
  1218. RefState::getRelinquished(Family,
  1219. ParentExpr));
  1220. return State->set<RegionState>(SymBase,
  1221. RefState::getReleased(Family, ParentExpr));
  1222. }
  1223. Optional<MallocChecker::CheckKind>
  1224. MallocChecker::getCheckIfTracked(AllocationFamily Family,
  1225. bool IsALeakCheck) const {
  1226. switch (Family) {
  1227. case AF_Malloc:
  1228. case AF_Alloca:
  1229. case AF_IfNameIndex: {
  1230. if (ChecksEnabled[CK_MallocChecker])
  1231. return CK_MallocChecker;
  1232. return Optional<MallocChecker::CheckKind>();
  1233. }
  1234. case AF_CXXNew:
  1235. case AF_CXXNewArray: {
  1236. if (IsALeakCheck) {
  1237. if (ChecksEnabled[CK_NewDeleteLeaksChecker])
  1238. return CK_NewDeleteLeaksChecker;
  1239. }
  1240. else {
  1241. if (ChecksEnabled[CK_NewDeleteChecker])
  1242. return CK_NewDeleteChecker;
  1243. }
  1244. return Optional<MallocChecker::CheckKind>();
  1245. }
  1246. case AF_None: {
  1247. llvm_unreachable("no family");
  1248. }
  1249. }
  1250. llvm_unreachable("unhandled family");
  1251. }
  1252. Optional<MallocChecker::CheckKind>
  1253. MallocChecker::getCheckIfTracked(CheckerContext &C,
  1254. const Stmt *AllocDeallocStmt,
  1255. bool IsALeakCheck) const {
  1256. return getCheckIfTracked(getAllocationFamily(C, AllocDeallocStmt),
  1257. IsALeakCheck);
  1258. }
  1259. Optional<MallocChecker::CheckKind>
  1260. MallocChecker::getCheckIfTracked(CheckerContext &C, SymbolRef Sym,
  1261. bool IsALeakCheck) const {
  1262. if (C.getState()->contains<ReallocSizeZeroSymbols>(Sym))
  1263. return CK_MallocChecker;
  1264. const RefState *RS = C.getState()->get<RegionState>(Sym);
  1265. assert(RS);
  1266. return getCheckIfTracked(RS->getAllocationFamily(), IsALeakCheck);
  1267. }
  1268. bool MallocChecker::SummarizeValue(raw_ostream &os, SVal V) {
  1269. if (Optional<nonloc::ConcreteInt> IntVal = V.getAs<nonloc::ConcreteInt>())
  1270. os << "an integer (" << IntVal->getValue() << ")";
  1271. else if (Optional<loc::ConcreteInt> ConstAddr = V.getAs<loc::ConcreteInt>())
  1272. os << "a constant address (" << ConstAddr->getValue() << ")";
  1273. else if (Optional<loc::GotoLabel> Label = V.getAs<loc::GotoLabel>())
  1274. os << "the address of the label '" << Label->getLabel()->getName() << "'";
  1275. else
  1276. return false;
  1277. return true;
  1278. }
  1279. bool MallocChecker::SummarizeRegion(raw_ostream &os,
  1280. const MemRegion *MR) {
  1281. switch (MR->getKind()) {
  1282. case MemRegion::FunctionTextRegionKind: {
  1283. const NamedDecl *FD = cast<FunctionTextRegion>(MR)->getDecl();
  1284. if (FD)
  1285. os << "the address of the function '" << *FD << '\'';
  1286. else
  1287. os << "the address of a function";
  1288. return true;
  1289. }
  1290. case MemRegion::BlockTextRegionKind:
  1291. os << "block text";
  1292. return true;
  1293. case MemRegion::BlockDataRegionKind:
  1294. // FIXME: where the block came from?
  1295. os << "a block";
  1296. return true;
  1297. default: {
  1298. const MemSpaceRegion *MS = MR->getMemorySpace();
  1299. if (isa<StackLocalsSpaceRegion>(MS)) {
  1300. const VarRegion *VR = dyn_cast<VarRegion>(MR);
  1301. const VarDecl *VD;
  1302. if (VR)
  1303. VD = VR->getDecl();
  1304. else
  1305. VD = nullptr;
  1306. if (VD)
  1307. os << "the address of the local variable '" << VD->getName() << "'";
  1308. else
  1309. os << "the address of a local stack variable";
  1310. return true;
  1311. }
  1312. if (isa<StackArgumentsSpaceRegion>(MS)) {
  1313. const VarRegion *VR = dyn_cast<VarRegion>(MR);
  1314. const VarDecl *VD;
  1315. if (VR)
  1316. VD = VR->getDecl();
  1317. else
  1318. VD = nullptr;
  1319. if (VD)
  1320. os << "the address of the parameter '" << VD->getName() << "'";
  1321. else
  1322. os << "the address of a parameter";
  1323. return true;
  1324. }
  1325. if (isa<GlobalsSpaceRegion>(MS)) {
  1326. const VarRegion *VR = dyn_cast<VarRegion>(MR);
  1327. const VarDecl *VD;
  1328. if (VR)
  1329. VD = VR->getDecl();
  1330. else
  1331. VD = nullptr;
  1332. if (VD) {
  1333. if (VD->isStaticLocal())
  1334. os << "the address of the static variable '" << VD->getName() << "'";
  1335. else
  1336. os << "the address of the global variable '" << VD->getName() << "'";
  1337. } else
  1338. os << "the address of a global variable";
  1339. return true;
  1340. }
  1341. return false;
  1342. }
  1343. }
  1344. }
  1345. void MallocChecker::ReportBadFree(CheckerContext &C, SVal ArgVal,
  1346. SourceRange Range,
  1347. const Expr *DeallocExpr) const {
  1348. if (!ChecksEnabled[CK_MallocChecker] &&
  1349. !ChecksEnabled[CK_NewDeleteChecker])
  1350. return;
  1351. Optional<MallocChecker::CheckKind> CheckKind =
  1352. getCheckIfTracked(C, DeallocExpr);
  1353. if (!CheckKind.hasValue())
  1354. return;
  1355. if (ExplodedNode *N = C.generateErrorNode()) {
  1356. if (!BT_BadFree[*CheckKind])
  1357. BT_BadFree[*CheckKind].reset(
  1358. new BugType(CheckNames[*CheckKind], "Bad free", "Memory Error"));
  1359. SmallString<100> buf;
  1360. llvm::raw_svector_ostream os(buf);
  1361. const MemRegion *MR = ArgVal.getAsRegion();
  1362. while (const ElementRegion *ER = dyn_cast_or_null<ElementRegion>(MR))
  1363. MR = ER->getSuperRegion();
  1364. os << "Argument to ";
  1365. if (!printAllocDeallocName(os, C, DeallocExpr))
  1366. os << "deallocator";
  1367. os << " is ";
  1368. bool Summarized = MR ? SummarizeRegion(os, MR)
  1369. : SummarizeValue(os, ArgVal);
  1370. if (Summarized)
  1371. os << ", which is not memory allocated by ";
  1372. else
  1373. os << "not memory allocated by ";
  1374. printExpectedAllocName(os, C, DeallocExpr);
  1375. auto R = llvm::make_unique<BugReport>(*BT_BadFree[*CheckKind], os.str(), N);
  1376. R->markInteresting(MR);
  1377. R->addRange(Range);
  1378. C.emitReport(std::move(R));
  1379. }
  1380. }
  1381. void MallocChecker::ReportFreeAlloca(CheckerContext &C, SVal ArgVal,
  1382. SourceRange Range) const {
  1383. Optional<MallocChecker::CheckKind> CheckKind;
  1384. if (ChecksEnabled[CK_MallocChecker])
  1385. CheckKind = CK_MallocChecker;
  1386. else if (ChecksEnabled[CK_MismatchedDeallocatorChecker])
  1387. CheckKind = CK_MismatchedDeallocatorChecker;
  1388. else
  1389. return;
  1390. if (ExplodedNode *N = C.generateErrorNode()) {
  1391. if (!BT_FreeAlloca[*CheckKind])
  1392. BT_FreeAlloca[*CheckKind].reset(
  1393. new BugType(CheckNames[*CheckKind], "Free alloca()", "Memory Error"));
  1394. auto R = llvm::make_unique<BugReport>(
  1395. *BT_FreeAlloca[*CheckKind],
  1396. "Memory allocated by alloca() should not be deallocated", N);
  1397. R->markInteresting(ArgVal.getAsRegion());
  1398. R->addRange(Range);
  1399. C.emitReport(std::move(R));
  1400. }
  1401. }
  1402. void MallocChecker::ReportMismatchedDealloc(CheckerContext &C,
  1403. SourceRange Range,
  1404. const Expr *DeallocExpr,
  1405. const RefState *RS,
  1406. SymbolRef Sym,
  1407. bool OwnershipTransferred) const {
  1408. if (!ChecksEnabled[CK_MismatchedDeallocatorChecker])
  1409. return;
  1410. if (ExplodedNode *N = C.generateErrorNode()) {
  1411. if (!BT_MismatchedDealloc)
  1412. BT_MismatchedDealloc.reset(
  1413. new BugType(CheckNames[CK_MismatchedDeallocatorChecker],
  1414. "Bad deallocator", "Memory Error"));
  1415. SmallString<100> buf;
  1416. llvm::raw_svector_ostream os(buf);
  1417. const Expr *AllocExpr = cast<Expr>(RS->getStmt());
  1418. SmallString<20> AllocBuf;
  1419. llvm::raw_svector_ostream AllocOs(AllocBuf);
  1420. SmallString<20> DeallocBuf;
  1421. llvm::raw_svector_ostream DeallocOs(DeallocBuf);
  1422. if (OwnershipTransferred) {
  1423. if (printAllocDeallocName(DeallocOs, C, DeallocExpr))
  1424. os << DeallocOs.str() << " cannot";
  1425. else
  1426. os << "Cannot";
  1427. os << " take ownership of memory";
  1428. if (printAllocDeallocName(AllocOs, C, AllocExpr))
  1429. os << " allocated by " << AllocOs.str();
  1430. } else {
  1431. os << "Memory";
  1432. if (printAllocDeallocName(AllocOs, C, AllocExpr))
  1433. os << " allocated by " << AllocOs.str();
  1434. os << " should be deallocated by ";
  1435. printExpectedDeallocName(os, RS->getAllocationFamily());
  1436. if (printAllocDeallocName(DeallocOs, C, DeallocExpr))
  1437. os << ", not " << DeallocOs.str();
  1438. }
  1439. auto R = llvm::make_unique<BugReport>(*BT_MismatchedDealloc, os.str(), N);
  1440. R->markInteresting(Sym);
  1441. R->addRange(Range);
  1442. R->addVisitor(llvm::make_unique<MallocBugVisitor>(Sym));
  1443. C.emitReport(std::move(R));
  1444. }
  1445. }
  1446. void MallocChecker::ReportOffsetFree(CheckerContext &C, SVal ArgVal,
  1447. SourceRange Range, const Expr *DeallocExpr,
  1448. const Expr *AllocExpr) const {
  1449. if (!ChecksEnabled[CK_MallocChecker] &&
  1450. !ChecksEnabled[CK_NewDeleteChecker])
  1451. return;
  1452. Optional<MallocChecker::CheckKind> CheckKind =
  1453. getCheckIfTracked(C, AllocExpr);
  1454. if (!CheckKind.hasValue())
  1455. return;
  1456. ExplodedNode *N = C.generateErrorNode();
  1457. if (!N)
  1458. return;
  1459. if (!BT_OffsetFree[*CheckKind])
  1460. BT_OffsetFree[*CheckKind].reset(
  1461. new BugType(CheckNames[*CheckKind], "Offset free", "Memory Error"));
  1462. SmallString<100> buf;
  1463. llvm::raw_svector_ostream os(buf);
  1464. SmallString<20> AllocNameBuf;
  1465. llvm::raw_svector_ostream AllocNameOs(AllocNameBuf);
  1466. const MemRegion *MR = ArgVal.getAsRegion();
  1467. assert(MR && "Only MemRegion based symbols can have offset free errors");
  1468. RegionOffset Offset = MR->getAsOffset();
  1469. assert((Offset.isValid() &&
  1470. !Offset.hasSymbolicOffset() &&
  1471. Offset.getOffset() != 0) &&
  1472. "Only symbols with a valid offset can have offset free errors");
  1473. int offsetBytes = Offset.getOffset() / C.getASTContext().getCharWidth();
  1474. os << "Argument to ";
  1475. if (!printAllocDeallocName(os, C, DeallocExpr))
  1476. os << "deallocator";
  1477. os << " is offset by "
  1478. << offsetBytes
  1479. << " "
  1480. << ((abs(offsetBytes) > 1) ? "bytes" : "byte")
  1481. << " from the start of ";
  1482. if (AllocExpr && printAllocDeallocName(AllocNameOs, C, AllocExpr))
  1483. os << "memory allocated by " << AllocNameOs.str();
  1484. else
  1485. os << "allocated memory";
  1486. auto R = llvm::make_unique<BugReport>(*BT_OffsetFree[*CheckKind], os.str(), N);
  1487. R->markInteresting(MR->getBaseRegion());
  1488. R->addRange(Range);
  1489. C.emitReport(std::move(R));
  1490. }
  1491. void MallocChecker::ReportUseAfterFree(CheckerContext &C, SourceRange Range,
  1492. SymbolRef Sym) const {
  1493. if (!ChecksEnabled[CK_MallocChecker] &&
  1494. !ChecksEnabled[CK_NewDeleteChecker])
  1495. return;
  1496. Optional<MallocChecker::CheckKind> CheckKind = getCheckIfTracked(C, Sym);
  1497. if (!CheckKind.hasValue())
  1498. return;
  1499. if (ExplodedNode *N = C.generateErrorNode()) {
  1500. if (!BT_UseFree[*CheckKind])
  1501. BT_UseFree[*CheckKind].reset(new BugType(
  1502. CheckNames[*CheckKind], "Use-after-free", "Memory Error"));
  1503. auto R = llvm::make_unique<BugReport>(*BT_UseFree[*CheckKind],
  1504. "Use of memory after it is freed", N);
  1505. R->markInteresting(Sym);
  1506. R->addRange(Range);
  1507. R->addVisitor(llvm::make_unique<MallocBugVisitor>(Sym));
  1508. C.emitReport(std::move(R));
  1509. }
  1510. }
  1511. void MallocChecker::ReportDoubleFree(CheckerContext &C, SourceRange Range,
  1512. bool Released, SymbolRef Sym,
  1513. SymbolRef PrevSym) const {
  1514. if (!ChecksEnabled[CK_MallocChecker] &&
  1515. !ChecksEnabled[CK_NewDeleteChecker])
  1516. return;
  1517. Optional<MallocChecker::CheckKind> CheckKind = getCheckIfTracked(C, Sym);
  1518. if (!CheckKind.hasValue())
  1519. return;
  1520. if (ExplodedNode *N = C.generateErrorNode()) {
  1521. if (!BT_DoubleFree[*CheckKind])
  1522. BT_DoubleFree[*CheckKind].reset(
  1523. new BugType(CheckNames[*CheckKind], "Double free", "Memory Error"));
  1524. auto R = llvm::make_unique<BugReport>(
  1525. *BT_DoubleFree[*CheckKind],
  1526. (Released ? "Attempt to free released memory"
  1527. : "Attempt to free non-owned memory"),
  1528. N);
  1529. R->addRange(Range);
  1530. R->markInteresting(Sym);
  1531. if (PrevSym)
  1532. R->markInteresting(PrevSym);
  1533. R->addVisitor(llvm::make_unique<MallocBugVisitor>(Sym));
  1534. C.emitReport(std::move(R));
  1535. }
  1536. }
  1537. void MallocChecker::ReportDoubleDelete(CheckerContext &C, SymbolRef Sym) const {
  1538. if (!ChecksEnabled[CK_NewDeleteChecker])
  1539. return;
  1540. Optional<MallocChecker::CheckKind> CheckKind = getCheckIfTracked(C, Sym);
  1541. if (!CheckKind.hasValue())
  1542. return;
  1543. if (ExplodedNode *N = C.generateErrorNode()) {
  1544. if (!BT_DoubleDelete)
  1545. BT_DoubleDelete.reset(new BugType(CheckNames[CK_NewDeleteChecker],
  1546. "Double delete", "Memory Error"));
  1547. auto R = llvm::make_unique<BugReport>(
  1548. *BT_DoubleDelete, "Attempt to delete released memory", N);
  1549. R->markInteresting(Sym);
  1550. R->addVisitor(llvm::make_unique<MallocBugVisitor>(Sym));
  1551. C.emitReport(std::move(R));
  1552. }
  1553. }
  1554. void MallocChecker::ReportUseZeroAllocated(CheckerContext &C,
  1555. SourceRange Range,
  1556. SymbolRef Sym) const {
  1557. if (!ChecksEnabled[CK_MallocChecker] &&
  1558. !ChecksEnabled[CK_NewDeleteChecker])
  1559. return;
  1560. Optional<MallocChecker::CheckKind> CheckKind = getCheckIfTracked(C, Sym);
  1561. if (!CheckKind.hasValue())
  1562. return;
  1563. if (ExplodedNode *N = C.generateErrorNode()) {
  1564. if (!BT_UseZerroAllocated[*CheckKind])
  1565. BT_UseZerroAllocated[*CheckKind].reset(new BugType(
  1566. CheckNames[*CheckKind], "Use of zero allocated", "Memory Error"));
  1567. auto R = llvm::make_unique<BugReport>(*BT_UseZerroAllocated[*CheckKind],
  1568. "Use of zero-allocated memory", N);
  1569. R->addRange(Range);
  1570. if (Sym) {
  1571. R->markInteresting(Sym);
  1572. R->addVisitor(llvm::make_unique<MallocBugVisitor>(Sym));
  1573. }
  1574. C.emitReport(std::move(R));
  1575. }
  1576. }
  1577. ProgramStateRef MallocChecker::ReallocMem(CheckerContext &C,
  1578. const CallExpr *CE,
  1579. bool FreesOnFail,
  1580. ProgramStateRef State) const {
  1581. if (!State)
  1582. return nullptr;
  1583. if (CE->getNumArgs() < 2)
  1584. return nullptr;
  1585. const Expr *arg0Expr = CE->getArg(0);
  1586. const LocationContext *LCtx = C.getLocationContext();
  1587. SVal Arg0Val = State->getSVal(arg0Expr, LCtx);
  1588. if (!Arg0Val.getAs<DefinedOrUnknownSVal>())
  1589. return nullptr;
  1590. DefinedOrUnknownSVal arg0Val = Arg0Val.castAs<DefinedOrUnknownSVal>();
  1591. SValBuilder &svalBuilder = C.getSValBuilder();
  1592. DefinedOrUnknownSVal PtrEQ =
  1593. svalBuilder.evalEQ(State, arg0Val, svalBuilder.makeNull());
  1594. // Get the size argument. If there is no size arg then give up.
  1595. const Expr *Arg1 = CE->getArg(1);
  1596. if (!Arg1)
  1597. return nullptr;
  1598. // Get the value of the size argument.
  1599. SVal Arg1ValG = State->getSVal(Arg1, LCtx);
  1600. if (!Arg1ValG.getAs<DefinedOrUnknownSVal>())
  1601. return nullptr;
  1602. DefinedOrUnknownSVal Arg1Val = Arg1ValG.castAs<DefinedOrUnknownSVal>();
  1603. // Compare the size argument to 0.
  1604. DefinedOrUnknownSVal SizeZero =
  1605. svalBuilder.evalEQ(State, Arg1Val,
  1606. svalBuilder.makeIntValWithPtrWidth(0, false));
  1607. ProgramStateRef StatePtrIsNull, StatePtrNotNull;
  1608. std::tie(StatePtrIsNull, StatePtrNotNull) = State->assume(PtrEQ);
  1609. ProgramStateRef StateSizeIsZero, StateSizeNotZero;
  1610. std::tie(StateSizeIsZero, StateSizeNotZero) = State->assume(SizeZero);
  1611. // We only assume exceptional states if they are definitely true; if the
  1612. // state is under-constrained, assume regular realloc behavior.
  1613. bool PrtIsNull = StatePtrIsNull && !StatePtrNotNull;
  1614. bool SizeIsZero = StateSizeIsZero && !StateSizeNotZero;
  1615. // If the ptr is NULL and the size is not 0, the call is equivalent to
  1616. // malloc(size).
  1617. if ( PrtIsNull && !SizeIsZero) {
  1618. ProgramStateRef stateMalloc = MallocMemAux(C, CE, CE->getArg(1),
  1619. UndefinedVal(), StatePtrIsNull);
  1620. return stateMalloc;
  1621. }
  1622. if (PrtIsNull && SizeIsZero)
  1623. return State;
  1624. // Get the from and to pointer symbols as in toPtr = realloc(fromPtr, size).
  1625. assert(!PrtIsNull);
  1626. SymbolRef FromPtr = arg0Val.getAsSymbol();
  1627. SVal RetVal = State->getSVal(CE, LCtx);
  1628. SymbolRef ToPtr = RetVal.getAsSymbol();
  1629. if (!FromPtr || !ToPtr)
  1630. return nullptr;
  1631. bool ReleasedAllocated = false;
  1632. // If the size is 0, free the memory.
  1633. if (SizeIsZero)
  1634. if (ProgramStateRef stateFree = FreeMemAux(C, CE, StateSizeIsZero, 0,
  1635. false, ReleasedAllocated)){
  1636. // The semantics of the return value are:
  1637. // If size was equal to 0, either NULL or a pointer suitable to be passed
  1638. // to free() is returned. We just free the input pointer and do not add
  1639. // any constrains on the output pointer.
  1640. return stateFree;
  1641. }
  1642. // Default behavior.
  1643. if (ProgramStateRef stateFree =
  1644. FreeMemAux(C, CE, State, 0, false, ReleasedAllocated)) {
  1645. ProgramStateRef stateRealloc = MallocMemAux(C, CE, CE->getArg(1),
  1646. UnknownVal(), stateFree);
  1647. if (!stateRealloc)
  1648. return nullptr;
  1649. ReallocPairKind Kind = RPToBeFreedAfterFailure;
  1650. if (FreesOnFail)
  1651. Kind = RPIsFreeOnFailure;
  1652. else if (!ReleasedAllocated)
  1653. Kind = RPDoNotTrackAfterFailure;
  1654. // Record the info about the reallocated symbol so that we could properly
  1655. // process failed reallocation.
  1656. stateRealloc = stateRealloc->set<ReallocPairs>(ToPtr,
  1657. ReallocPair(FromPtr, Kind));
  1658. // The reallocated symbol should stay alive for as long as the new symbol.
  1659. C.getSymbolManager().addSymbolDependency(ToPtr, FromPtr);
  1660. return stateRealloc;
  1661. }
  1662. return nullptr;
  1663. }
  1664. ProgramStateRef MallocChecker::CallocMem(CheckerContext &C, const CallExpr *CE,
  1665. ProgramStateRef State) {
  1666. if (!State)
  1667. return nullptr;
  1668. if (CE->getNumArgs() < 2)
  1669. return nullptr;
  1670. SValBuilder &svalBuilder = C.getSValBuilder();
  1671. const LocationContext *LCtx = C.getLocationContext();
  1672. SVal count = State->getSVal(CE->getArg(0), LCtx);
  1673. SVal elementSize = State->getSVal(CE->getArg(1), LCtx);
  1674. SVal TotalSize = svalBuilder.evalBinOp(State, BO_Mul, count, elementSize,
  1675. svalBuilder.getContext().getSizeType());
  1676. SVal zeroVal = svalBuilder.makeZeroVal(svalBuilder.getContext().CharTy);
  1677. return MallocMemAux(C, CE, TotalSize, zeroVal, State);
  1678. }
  1679. LeakInfo
  1680. MallocChecker::getAllocationSite(const ExplodedNode *N, SymbolRef Sym,
  1681. CheckerContext &C) const {
  1682. const LocationContext *LeakContext = N->getLocationContext();
  1683. // Walk the ExplodedGraph backwards and find the first node that referred to
  1684. // the tracked symbol.
  1685. const ExplodedNode *AllocNode = N;
  1686. const MemRegion *ReferenceRegion = nullptr;
  1687. while (N) {
  1688. ProgramStateRef State = N->getState();
  1689. if (!State->get<RegionState>(Sym))
  1690. break;
  1691. // Find the most recent expression bound to the symbol in the current
  1692. // context.
  1693. if (!ReferenceRegion) {
  1694. if (const MemRegion *MR = C.getLocationRegionIfPostStore(N)) {
  1695. SVal Val = State->getSVal(MR);
  1696. if (Val.getAsLocSymbol() == Sym) {
  1697. const VarRegion* VR = MR->getBaseRegion()->getAs<VarRegion>();
  1698. // Do not show local variables belonging to a function other than
  1699. // where the error is reported.
  1700. if (!VR ||
  1701. (VR->getStackFrame() == LeakContext->getCurrentStackFrame()))
  1702. ReferenceRegion = MR;
  1703. }
  1704. }
  1705. }
  1706. // Allocation node, is the last node in the current or parent context in
  1707. // which the symbol was tracked.
  1708. const LocationContext *NContext = N->getLocationContext();
  1709. if (NContext == LeakContext ||
  1710. NContext->isParentOf(LeakContext))
  1711. AllocNode = N;
  1712. N = N->pred_empty() ? nullptr : *(N->pred_begin());
  1713. }
  1714. return LeakInfo(AllocNode, ReferenceRegion);
  1715. }
  1716. void MallocChecker::reportLeak(SymbolRef Sym, ExplodedNode *N,
  1717. CheckerContext &C) const {
  1718. if (!ChecksEnabled[CK_MallocChecker] &&
  1719. !ChecksEnabled[CK_NewDeleteLeaksChecker])
  1720. return;
  1721. const RefState *RS = C.getState()->get<RegionState>(Sym);
  1722. assert(RS && "cannot leak an untracked symbol");
  1723. AllocationFamily Family = RS->getAllocationFamily();
  1724. if (Family == AF_Alloca)
  1725. return;
  1726. Optional<MallocChecker::CheckKind>
  1727. CheckKind = getCheckIfTracked(Family, true);
  1728. if (!CheckKind.hasValue())
  1729. return;
  1730. assert(N);
  1731. if (!BT_Leak[*CheckKind]) {
  1732. BT_Leak[*CheckKind].reset(
  1733. new BugType(CheckNames[*CheckKind], "Memory leak", "Memory Error"));
  1734. // Leaks should not be reported if they are post-dominated by a sink:
  1735. // (1) Sinks are higher importance bugs.
  1736. // (2) NoReturnFunctionChecker uses sink nodes to represent paths ending
  1737. // with __noreturn functions such as assert() or exit(). We choose not
  1738. // to report leaks on such paths.
  1739. BT_Leak[*CheckKind]->setSuppressOnSink(true);
  1740. }
  1741. // Most bug reports are cached at the location where they occurred.
  1742. // With leaks, we want to unique them by the location where they were
  1743. // allocated, and only report a single path.
  1744. PathDiagnosticLocation LocUsedForUniqueing;
  1745. const ExplodedNode *AllocNode = nullptr;
  1746. const MemRegion *Region = nullptr;
  1747. std::tie(AllocNode, Region) = getAllocationSite(N, Sym, C);
  1748. ProgramPoint P = AllocNode->getLocation();
  1749. const Stmt *AllocationStmt = nullptr;
  1750. if (Optional<CallExitEnd> Exit = P.getAs<CallExitEnd>())
  1751. AllocationStmt = Exit->getCalleeContext()->getCallSite();
  1752. else if (Optional<StmtPoint> SP = P.getAs<StmtPoint>())
  1753. AllocationStmt = SP->getStmt();
  1754. if (AllocationStmt)
  1755. LocUsedForUniqueing = PathDiagnosticLocation::createBegin(AllocationStmt,
  1756. C.getSourceManager(),
  1757. AllocNode->getLocationContext());
  1758. SmallString<200> buf;
  1759. llvm::raw_svector_ostream os(buf);
  1760. if (Region && Region->canPrintPretty()) {
  1761. os << "Potential leak of memory pointed to by ";
  1762. Region->printPretty(os);
  1763. } else {
  1764. os << "Potential memory leak";
  1765. }
  1766. auto R = llvm::make_unique<BugReport>(
  1767. *BT_Leak[*CheckKind], os.str(), N, LocUsedForUniqueing,
  1768. AllocNode->getLocationContext()->getDecl());
  1769. R->markInteresting(Sym);
  1770. R->addVisitor(llvm::make_unique<MallocBugVisitor>(Sym, true));
  1771. C.emitReport(std::move(R));
  1772. }
  1773. void MallocChecker::checkDeadSymbols(SymbolReaper &SymReaper,
  1774. CheckerContext &C) const
  1775. {
  1776. if (!SymReaper.hasDeadSymbols())
  1777. return;
  1778. ProgramStateRef state = C.getState();
  1779. RegionStateTy RS = state->get<RegionState>();
  1780. RegionStateTy::Factory &F = state->get_context<RegionState>();
  1781. SmallVector<SymbolRef, 2> Errors;
  1782. for (RegionStateTy::iterator I = RS.begin(), E = RS.end(); I != E; ++I) {
  1783. if (SymReaper.isDead(I->first)) {
  1784. if (I->second.isAllocated() || I->second.isAllocatedOfSizeZero())
  1785. Errors.push_back(I->first);
  1786. // Remove the dead symbol from the map.
  1787. RS = F.remove(RS, I->first);
  1788. }
  1789. }
  1790. // Cleanup the Realloc Pairs Map.
  1791. ReallocPairsTy RP = state->get<ReallocPairs>();
  1792. for (ReallocPairsTy::iterator I = RP.begin(), E = RP.end(); I != E; ++I) {
  1793. if (SymReaper.isDead(I->first) ||
  1794. SymReaper.isDead(I->second.ReallocatedSym)) {
  1795. state = state->remove<ReallocPairs>(I->first);
  1796. }
  1797. }
  1798. // Cleanup the FreeReturnValue Map.
  1799. FreeReturnValueTy FR = state->get<FreeReturnValue>();
  1800. for (FreeReturnValueTy::iterator I = FR.begin(), E = FR.end(); I != E; ++I) {
  1801. if (SymReaper.isDead(I->first) ||
  1802. SymReaper.isDead(I->second)) {
  1803. state = state->remove<FreeReturnValue>(I->first);
  1804. }
  1805. }
  1806. // Generate leak node.
  1807. ExplodedNode *N = C.getPredecessor();
  1808. if (!Errors.empty()) {
  1809. static CheckerProgramPointTag Tag("MallocChecker", "DeadSymbolsLeak");
  1810. N = C.generateNonFatalErrorNode(C.getState(), &Tag);
  1811. if (N) {
  1812. for (SmallVectorImpl<SymbolRef>::iterator
  1813. I = Errors.begin(), E = Errors.end(); I != E; ++I) {
  1814. reportLeak(*I, N, C);
  1815. }
  1816. }
  1817. }
  1818. C.addTransition(state->set<RegionState>(RS), N);
  1819. }
  1820. void MallocChecker::checkPreCall(const CallEvent &Call,
  1821. CheckerContext &C) const {
  1822. if (const CXXDestructorCall *DC = dyn_cast<CXXDestructorCall>(&Call)) {
  1823. SymbolRef Sym = DC->getCXXThisVal().getAsSymbol();
  1824. if (!Sym || checkDoubleDelete(Sym, C))
  1825. return;
  1826. }
  1827. // We will check for double free in the post visit.
  1828. if (const AnyFunctionCall *FC = dyn_cast<AnyFunctionCall>(&Call)) {
  1829. const FunctionDecl *FD = FC->getDecl();
  1830. if (!FD)
  1831. return;
  1832. ASTContext &Ctx = C.getASTContext();
  1833. if (ChecksEnabled[CK_MallocChecker] &&
  1834. (isCMemFunction(FD, Ctx, AF_Malloc, MemoryOperationKind::MOK_Free) ||
  1835. isCMemFunction(FD, Ctx, AF_IfNameIndex,
  1836. MemoryOperationKind::MOK_Free)))
  1837. return;
  1838. if (ChecksEnabled[CK_NewDeleteChecker] &&
  1839. isStandardNewDelete(FD, Ctx))
  1840. return;
  1841. }
  1842. // Check if the callee of a method is deleted.
  1843. if (const CXXInstanceCall *CC = dyn_cast<CXXInstanceCall>(&Call)) {
  1844. SymbolRef Sym = CC->getCXXThisVal().getAsSymbol();
  1845. if (!Sym || checkUseAfterFree(Sym, C, CC->getCXXThisExpr()))
  1846. return;
  1847. }
  1848. // Check arguments for being used after free.
  1849. for (unsigned I = 0, E = Call.getNumArgs(); I != E; ++I) {
  1850. SVal ArgSVal = Call.getArgSVal(I);
  1851. if (ArgSVal.getAs<Loc>()) {
  1852. SymbolRef Sym = ArgSVal.getAsSymbol();
  1853. if (!Sym)
  1854. continue;
  1855. if (checkUseAfterFree(Sym, C, Call.getArgExpr(I)))
  1856. return;
  1857. }
  1858. }
  1859. }
  1860. void MallocChecker::checkPreStmt(const ReturnStmt *S, CheckerContext &C) const {
  1861. const Expr *E = S->getRetValue();
  1862. if (!E)
  1863. return;
  1864. // Check if we are returning a symbol.
  1865. ProgramStateRef State = C.getState();
  1866. SVal RetVal = State->getSVal(E, C.getLocationContext());
  1867. SymbolRef Sym = RetVal.getAsSymbol();
  1868. if (!Sym)
  1869. // If we are returning a field of the allocated struct or an array element,
  1870. // the callee could still free the memory.
  1871. // TODO: This logic should be a part of generic symbol escape callback.
  1872. if (const MemRegion *MR = RetVal.getAsRegion())
  1873. if (isa<FieldRegion>(MR) || isa<ElementRegion>(MR))
  1874. if (const SymbolicRegion *BMR =
  1875. dyn_cast<SymbolicRegion>(MR->getBaseRegion()))
  1876. Sym = BMR->getSymbol();
  1877. // Check if we are returning freed memory.
  1878. if (Sym)
  1879. checkUseAfterFree(Sym, C, E);
  1880. }
  1881. // TODO: Blocks should be either inlined or should call invalidate regions
  1882. // upon invocation. After that's in place, special casing here will not be
  1883. // needed.
  1884. void MallocChecker::checkPostStmt(const BlockExpr *BE,
  1885. CheckerContext &C) const {
  1886. // Scan the BlockDecRefExprs for any object the retain count checker
  1887. // may be tracking.
  1888. if (!BE->getBlockDecl()->hasCaptures())
  1889. return;
  1890. ProgramStateRef state = C.getState();
  1891. const BlockDataRegion *R =
  1892. cast<BlockDataRegion>(state->getSVal(BE,
  1893. C.getLocationContext()).getAsRegion());
  1894. BlockDataRegion::referenced_vars_iterator I = R->referenced_vars_begin(),
  1895. E = R->referenced_vars_end();
  1896. if (I == E)
  1897. return;
  1898. SmallVector<const MemRegion*, 10> Regions;
  1899. const LocationContext *LC = C.getLocationContext();
  1900. MemRegionManager &MemMgr = C.getSValBuilder().getRegionManager();
  1901. for ( ; I != E; ++I) {
  1902. const VarRegion *VR = I.getCapturedRegion();
  1903. if (VR->getSuperRegion() == R) {
  1904. VR = MemMgr.getVarRegion(VR->getDecl(), LC);
  1905. }
  1906. Regions.push_back(VR);
  1907. }
  1908. state =
  1909. state->scanReachableSymbols<StopTrackingCallback>(Regions.data(),
  1910. Regions.data() + Regions.size()).getState();
  1911. C.addTransition(state);
  1912. }
  1913. bool MallocChecker::isReleased(SymbolRef Sym, CheckerContext &C) const {
  1914. assert(Sym);
  1915. const RefState *RS = C.getState()->get<RegionState>(Sym);
  1916. return (RS && RS->isReleased());
  1917. }
  1918. bool MallocChecker::checkUseAfterFree(SymbolRef Sym, CheckerContext &C,
  1919. const Stmt *S) const {
  1920. if (isReleased(Sym, C)) {
  1921. ReportUseAfterFree(C, S->getSourceRange(), Sym);
  1922. return true;
  1923. }
  1924. return false;
  1925. }
  1926. void MallocChecker::checkUseZeroAllocated(SymbolRef Sym, CheckerContext &C,
  1927. const Stmt *S) const {
  1928. assert(Sym);
  1929. if (const RefState *RS = C.getState()->get<RegionState>(Sym)) {
  1930. if (RS->isAllocatedOfSizeZero())
  1931. ReportUseZeroAllocated(C, RS->getStmt()->getSourceRange(), Sym);
  1932. }
  1933. else if (C.getState()->contains<ReallocSizeZeroSymbols>(Sym)) {
  1934. ReportUseZeroAllocated(C, S->getSourceRange(), Sym);
  1935. }
  1936. }
  1937. bool MallocChecker::checkDoubleDelete(SymbolRef Sym, CheckerContext &C) const {
  1938. if (isReleased(Sym, C)) {
  1939. ReportDoubleDelete(C, Sym);
  1940. return true;
  1941. }
  1942. return false;
  1943. }
  1944. // Check if the location is a freed symbolic region.
  1945. void MallocChecker::checkLocation(SVal l, bool isLoad, const Stmt *S,
  1946. CheckerContext &C) const {
  1947. SymbolRef Sym = l.getLocSymbolInBase();
  1948. if (Sym) {
  1949. checkUseAfterFree(Sym, C, S);
  1950. checkUseZeroAllocated(Sym, C, S);
  1951. }
  1952. }
  1953. // If a symbolic region is assumed to NULL (or another constant), stop tracking
  1954. // it - assuming that allocation failed on this path.
  1955. ProgramStateRef MallocChecker::evalAssume(ProgramStateRef state,
  1956. SVal Cond,
  1957. bool Assumption) const {
  1958. RegionStateTy RS = state->get<RegionState>();
  1959. for (RegionStateTy::iterator I = RS.begin(), E = RS.end(); I != E; ++I) {
  1960. // If the symbol is assumed to be NULL, remove it from consideration.
  1961. ConstraintManager &CMgr = state->getConstraintManager();
  1962. ConditionTruthVal AllocFailed = CMgr.isNull(state, I.getKey());
  1963. if (AllocFailed.isConstrainedTrue())
  1964. state = state->remove<RegionState>(I.getKey());
  1965. }
  1966. // Realloc returns 0 when reallocation fails, which means that we should
  1967. // restore the state of the pointer being reallocated.
  1968. ReallocPairsTy RP = state->get<ReallocPairs>();
  1969. for (ReallocPairsTy::iterator I = RP.begin(), E = RP.end(); I != E; ++I) {
  1970. // If the symbol is assumed to be NULL, remove it from consideration.
  1971. ConstraintManager &CMgr = state->getConstraintManager();
  1972. ConditionTruthVal AllocFailed = CMgr.isNull(state, I.getKey());
  1973. if (!AllocFailed.isConstrainedTrue())
  1974. continue;
  1975. SymbolRef ReallocSym = I.getData().ReallocatedSym;
  1976. if (const RefState *RS = state->get<RegionState>(ReallocSym)) {
  1977. if (RS->isReleased()) {
  1978. if (I.getData().Kind == RPToBeFreedAfterFailure)
  1979. state = state->set<RegionState>(ReallocSym,
  1980. RefState::getAllocated(RS->getAllocationFamily(), RS->getStmt()));
  1981. else if (I.getData().Kind == RPDoNotTrackAfterFailure)
  1982. state = state->remove<RegionState>(ReallocSym);
  1983. else
  1984. assert(I.getData().Kind == RPIsFreeOnFailure);
  1985. }
  1986. }
  1987. state = state->remove<ReallocPairs>(I.getKey());
  1988. }
  1989. return state;
  1990. }
  1991. bool MallocChecker::mayFreeAnyEscapedMemoryOrIsModeledExplicitly(
  1992. const CallEvent *Call,
  1993. ProgramStateRef State,
  1994. SymbolRef &EscapingSymbol) const {
  1995. assert(Call);
  1996. EscapingSymbol = nullptr;
  1997. // For now, assume that any C++ or block call can free memory.
  1998. // TODO: If we want to be more optimistic here, we'll need to make sure that
  1999. // regions escape to C++ containers. They seem to do that even now, but for
  2000. // mysterious reasons.
  2001. if (!(isa<SimpleFunctionCall>(Call) || isa<ObjCMethodCall>(Call)))
  2002. return true;
  2003. // Check Objective-C messages by selector name.
  2004. if (const ObjCMethodCall *Msg = dyn_cast<ObjCMethodCall>(Call)) {
  2005. // If it's not a framework call, or if it takes a callback, assume it
  2006. // can free memory.
  2007. if (!Call->isInSystemHeader() || Call->argumentsMayEscape())
  2008. return true;
  2009. // If it's a method we know about, handle it explicitly post-call.
  2010. // This should happen before the "freeWhenDone" check below.
  2011. if (isKnownDeallocObjCMethodName(*Msg))
  2012. return false;
  2013. // If there's a "freeWhenDone" parameter, but the method isn't one we know
  2014. // about, we can't be sure that the object will use free() to deallocate the
  2015. // memory, so we can't model it explicitly. The best we can do is use it to
  2016. // decide whether the pointer escapes.
  2017. if (Optional<bool> FreeWhenDone = getFreeWhenDoneArg(*Msg))
  2018. return *FreeWhenDone;
  2019. // If the first selector piece ends with "NoCopy", and there is no
  2020. // "freeWhenDone" parameter set to zero, we know ownership is being
  2021. // transferred. Again, though, we can't be sure that the object will use
  2022. // free() to deallocate the memory, so we can't model it explicitly.
  2023. StringRef FirstSlot = Msg->getSelector().getNameForSlot(0);
  2024. if (FirstSlot.endswith("NoCopy"))
  2025. return true;
  2026. // If the first selector starts with addPointer, insertPointer,
  2027. // or replacePointer, assume we are dealing with NSPointerArray or similar.
  2028. // This is similar to C++ containers (vector); we still might want to check
  2029. // that the pointers get freed by following the container itself.
  2030. if (FirstSlot.startswith("addPointer") ||
  2031. FirstSlot.startswith("insertPointer") ||
  2032. FirstSlot.startswith("replacePointer") ||
  2033. FirstSlot.equals("valueWithPointer")) {
  2034. return true;
  2035. }
  2036. // We should escape receiver on call to 'init'. This is especially relevant
  2037. // to the receiver, as the corresponding symbol is usually not referenced
  2038. // after the call.
  2039. if (Msg->getMethodFamily() == OMF_init) {
  2040. EscapingSymbol = Msg->getReceiverSVal().getAsSymbol();
  2041. return true;
  2042. }
  2043. // Otherwise, assume that the method does not free memory.
  2044. // Most framework methods do not free memory.
  2045. return false;
  2046. }
  2047. // At this point the only thing left to handle is straight function calls.
  2048. const FunctionDecl *FD = cast<SimpleFunctionCall>(Call)->getDecl();
  2049. if (!FD)
  2050. return true;
  2051. ASTContext &ASTC = State->getStateManager().getContext();
  2052. // If it's one of the allocation functions we can reason about, we model
  2053. // its behavior explicitly.
  2054. if (isMemFunction(FD, ASTC))
  2055. return false;
  2056. // If it's not a system call, assume it frees memory.
  2057. if (!Call->isInSystemHeader())
  2058. return true;
  2059. // White list the system functions whose arguments escape.
  2060. const IdentifierInfo *II = FD->getIdentifier();
  2061. if (!II)
  2062. return true;
  2063. StringRef FName = II->getName();
  2064. // White list the 'XXXNoCopy' CoreFoundation functions.
  2065. // We specifically check these before
  2066. if (FName.endswith("NoCopy")) {
  2067. // Look for the deallocator argument. We know that the memory ownership
  2068. // is not transferred only if the deallocator argument is
  2069. // 'kCFAllocatorNull'.
  2070. for (unsigned i = 1; i < Call->getNumArgs(); ++i) {
  2071. const Expr *ArgE = Call->getArgExpr(i)->IgnoreParenCasts();
  2072. if (const DeclRefExpr *DE = dyn_cast<DeclRefExpr>(ArgE)) {
  2073. StringRef DeallocatorName = DE->getFoundDecl()->getName();
  2074. if (DeallocatorName == "kCFAllocatorNull")
  2075. return false;
  2076. }
  2077. }
  2078. return true;
  2079. }
  2080. // Associating streams with malloced buffers. The pointer can escape if
  2081. // 'closefn' is specified (and if that function does free memory),
  2082. // but it will not if closefn is not specified.
  2083. // Currently, we do not inspect the 'closefn' function (PR12101).
  2084. if (FName == "funopen")
  2085. if (Call->getNumArgs() >= 4 && Call->getArgSVal(4).isConstant(0))
  2086. return false;
  2087. // Do not warn on pointers passed to 'setbuf' when used with std streams,
  2088. // these leaks might be intentional when setting the buffer for stdio.
  2089. // http://stackoverflow.com/questions/2671151/who-frees-setvbuf-buffer
  2090. if (FName == "setbuf" || FName =="setbuffer" ||
  2091. FName == "setlinebuf" || FName == "setvbuf") {
  2092. if (Call->getNumArgs() >= 1) {
  2093. const Expr *ArgE = Call->getArgExpr(0)->IgnoreParenCasts();
  2094. if (const DeclRefExpr *ArgDRE = dyn_cast<DeclRefExpr>(ArgE))
  2095. if (const VarDecl *D = dyn_cast<VarDecl>(ArgDRE->getDecl()))
  2096. if (D->getCanonicalDecl()->getName().find("std") != StringRef::npos)
  2097. return true;
  2098. }
  2099. }
  2100. // A bunch of other functions which either take ownership of a pointer or
  2101. // wrap the result up in a struct or object, meaning it can be freed later.
  2102. // (See RetainCountChecker.) Not all the parameters here are invalidated,
  2103. // but the Malloc checker cannot differentiate between them. The right way
  2104. // of doing this would be to implement a pointer escapes callback.
  2105. if (FName == "CGBitmapContextCreate" ||
  2106. FName == "CGBitmapContextCreateWithData" ||
  2107. FName == "CVPixelBufferCreateWithBytes" ||
  2108. FName == "CVPixelBufferCreateWithPlanarBytes" ||
  2109. FName == "OSAtomicEnqueue") {
  2110. return true;
  2111. }
  2112. // Handle cases where we know a buffer's /address/ can escape.
  2113. // Note that the above checks handle some special cases where we know that
  2114. // even though the address escapes, it's still our responsibility to free the
  2115. // buffer.
  2116. if (Call->argumentsMayEscape())
  2117. return true;
  2118. // Otherwise, assume that the function does not free memory.
  2119. // Most system calls do not free the memory.
  2120. return false;
  2121. }
  2122. static bool retTrue(const RefState *RS) {
  2123. return true;
  2124. }
  2125. static bool checkIfNewOrNewArrayFamily(const RefState *RS) {
  2126. return (RS->getAllocationFamily() == AF_CXXNewArray ||
  2127. RS->getAllocationFamily() == AF_CXXNew);
  2128. }
  2129. ProgramStateRef MallocChecker::checkPointerEscape(ProgramStateRef State,
  2130. const InvalidatedSymbols &Escaped,
  2131. const CallEvent *Call,
  2132. PointerEscapeKind Kind) const {
  2133. return checkPointerEscapeAux(State, Escaped, Call, Kind, &retTrue);
  2134. }
  2135. ProgramStateRef MallocChecker::checkConstPointerEscape(ProgramStateRef State,
  2136. const InvalidatedSymbols &Escaped,
  2137. const CallEvent *Call,
  2138. PointerEscapeKind Kind) const {
  2139. return checkPointerEscapeAux(State, Escaped, Call, Kind,
  2140. &checkIfNewOrNewArrayFamily);
  2141. }
  2142. ProgramStateRef MallocChecker::checkPointerEscapeAux(ProgramStateRef State,
  2143. const InvalidatedSymbols &Escaped,
  2144. const CallEvent *Call,
  2145. PointerEscapeKind Kind,
  2146. bool(*CheckRefState)(const RefState*)) const {
  2147. // If we know that the call does not free memory, or we want to process the
  2148. // call later, keep tracking the top level arguments.
  2149. SymbolRef EscapingSymbol = nullptr;
  2150. if (Kind == PSK_DirectEscapeOnCall &&
  2151. !mayFreeAnyEscapedMemoryOrIsModeledExplicitly(Call, State,
  2152. EscapingSymbol) &&
  2153. !EscapingSymbol) {
  2154. return State;
  2155. }
  2156. for (InvalidatedSymbols::const_iterator I = Escaped.begin(),
  2157. E = Escaped.end();
  2158. I != E; ++I) {
  2159. SymbolRef sym = *I;
  2160. if (EscapingSymbol && EscapingSymbol != sym)
  2161. continue;
  2162. if (const RefState *RS = State->get<RegionState>(sym)) {
  2163. if ((RS->isAllocated() || RS->isAllocatedOfSizeZero()) &&
  2164. CheckRefState(RS)) {
  2165. State = State->remove<RegionState>(sym);
  2166. State = State->set<RegionState>(sym, RefState::getEscaped(RS));
  2167. }
  2168. }
  2169. }
  2170. return State;
  2171. }
  2172. static SymbolRef findFailedReallocSymbol(ProgramStateRef currState,
  2173. ProgramStateRef prevState) {
  2174. ReallocPairsTy currMap = currState->get<ReallocPairs>();
  2175. ReallocPairsTy prevMap = prevState->get<ReallocPairs>();
  2176. for (ReallocPairsTy::iterator I = prevMap.begin(), E = prevMap.end();
  2177. I != E; ++I) {
  2178. SymbolRef sym = I.getKey();
  2179. if (!currMap.lookup(sym))
  2180. return sym;
  2181. }
  2182. return nullptr;
  2183. }
  2184. PathDiagnosticPiece *
  2185. MallocChecker::MallocBugVisitor::VisitNode(const ExplodedNode *N,
  2186. const ExplodedNode *PrevN,
  2187. BugReporterContext &BRC,
  2188. BugReport &BR) {
  2189. ProgramStateRef state = N->getState();
  2190. ProgramStateRef statePrev = PrevN->getState();
  2191. const RefState *RS = state->get<RegionState>(Sym);
  2192. const RefState *RSPrev = statePrev->get<RegionState>(Sym);
  2193. if (!RS)
  2194. return nullptr;
  2195. const Stmt *S = nullptr;
  2196. const char *Msg = nullptr;
  2197. StackHintGeneratorForSymbol *StackHint = nullptr;
  2198. // Retrieve the associated statement.
  2199. ProgramPoint ProgLoc = N->getLocation();
  2200. if (Optional<StmtPoint> SP = ProgLoc.getAs<StmtPoint>()) {
  2201. S = SP->getStmt();
  2202. } else if (Optional<CallExitEnd> Exit = ProgLoc.getAs<CallExitEnd>()) {
  2203. S = Exit->getCalleeContext()->getCallSite();
  2204. } else if (Optional<BlockEdge> Edge = ProgLoc.getAs<BlockEdge>()) {
  2205. // If an assumption was made on a branch, it should be caught
  2206. // here by looking at the state transition.
  2207. S = Edge->getSrc()->getTerminator();
  2208. }
  2209. if (!S)
  2210. return nullptr;
  2211. // FIXME: We will eventually need to handle non-statement-based events
  2212. // (__attribute__((cleanup))).
  2213. // Find out if this is an interesting point and what is the kind.
  2214. if (Mode == Normal) {
  2215. if (isAllocated(RS, RSPrev, S)) {
  2216. Msg = "Memory is allocated";
  2217. StackHint = new StackHintGeneratorForSymbol(Sym,
  2218. "Returned allocated memory");
  2219. } else if (isReleased(RS, RSPrev, S)) {
  2220. Msg = "Memory is released";
  2221. StackHint = new StackHintGeneratorForSymbol(Sym,
  2222. "Returning; memory was released");
  2223. } else if (isRelinquished(RS, RSPrev, S)) {
  2224. Msg = "Memory ownership is transferred";
  2225. StackHint = new StackHintGeneratorForSymbol(Sym, "");
  2226. } else if (isReallocFailedCheck(RS, RSPrev, S)) {
  2227. Mode = ReallocationFailed;
  2228. Msg = "Reallocation failed";
  2229. StackHint = new StackHintGeneratorForReallocationFailed(Sym,
  2230. "Reallocation failed");
  2231. if (SymbolRef sym = findFailedReallocSymbol(state, statePrev)) {
  2232. // Is it possible to fail two reallocs WITHOUT testing in between?
  2233. assert((!FailedReallocSymbol || FailedReallocSymbol == sym) &&
  2234. "We only support one failed realloc at a time.");
  2235. BR.markInteresting(sym);
  2236. FailedReallocSymbol = sym;
  2237. }
  2238. }
  2239. // We are in a special mode if a reallocation failed later in the path.
  2240. } else if (Mode == ReallocationFailed) {
  2241. assert(FailedReallocSymbol && "No symbol to look for.");
  2242. // Is this is the first appearance of the reallocated symbol?
  2243. if (!statePrev->get<RegionState>(FailedReallocSymbol)) {
  2244. // We're at the reallocation point.
  2245. Msg = "Attempt to reallocate memory";
  2246. StackHint = new StackHintGeneratorForSymbol(Sym,
  2247. "Returned reallocated memory");
  2248. FailedReallocSymbol = nullptr;
  2249. Mode = Normal;
  2250. }
  2251. }
  2252. if (!Msg)
  2253. return nullptr;
  2254. assert(StackHint);
  2255. // Generate the extra diagnostic.
  2256. PathDiagnosticLocation Pos(S, BRC.getSourceManager(),
  2257. N->getLocationContext());
  2258. return new PathDiagnosticEventPiece(Pos, Msg, true, StackHint);
  2259. }
  2260. void MallocChecker::printState(raw_ostream &Out, ProgramStateRef State,
  2261. const char *NL, const char *Sep) const {
  2262. RegionStateTy RS = State->get<RegionState>();
  2263. if (!RS.isEmpty()) {
  2264. Out << Sep << "MallocChecker :" << NL;
  2265. for (RegionStateTy::iterator I = RS.begin(), E = RS.end(); I != E; ++I) {
  2266. const RefState *RefS = State->get<RegionState>(I.getKey());
  2267. AllocationFamily Family = RefS->getAllocationFamily();
  2268. Optional<MallocChecker::CheckKind> CheckKind = getCheckIfTracked(Family);
  2269. if (!CheckKind.hasValue())
  2270. CheckKind = getCheckIfTracked(Family, true);
  2271. I.getKey()->dumpToStream(Out);
  2272. Out << " : ";
  2273. I.getData().dump(Out);
  2274. if (CheckKind.hasValue())
  2275. Out << " (" << CheckNames[*CheckKind].getName() << ")";
  2276. Out << NL;
  2277. }
  2278. }
  2279. }
  2280. void ento::registerNewDeleteLeaksChecker(CheckerManager &mgr) {
  2281. registerCStringCheckerBasic(mgr);
  2282. MallocChecker *checker = mgr.registerChecker<MallocChecker>();
  2283. checker->IsOptimistic = mgr.getAnalyzerOptions().getBooleanOption(
  2284. "Optimistic", false, checker);
  2285. checker->ChecksEnabled[MallocChecker::CK_NewDeleteLeaksChecker] = true;
  2286. checker->CheckNames[MallocChecker::CK_NewDeleteLeaksChecker] =
  2287. mgr.getCurrentCheckName();
  2288. // We currently treat NewDeleteLeaks checker as a subchecker of NewDelete
  2289. // checker.
  2290. if (!checker->ChecksEnabled[MallocChecker::CK_NewDeleteChecker])
  2291. checker->ChecksEnabled[MallocChecker::CK_NewDeleteChecker] = true;
  2292. }
  2293. #define REGISTER_CHECKER(name) \
  2294. void ento::register##name(CheckerManager &mgr) { \
  2295. registerCStringCheckerBasic(mgr); \
  2296. MallocChecker *checker = mgr.registerChecker<MallocChecker>(); \
  2297. checker->IsOptimistic = mgr.getAnalyzerOptions().getBooleanOption( \
  2298. "Optimistic", false, checker); \
  2299. checker->ChecksEnabled[MallocChecker::CK_##name] = true; \
  2300. checker->CheckNames[MallocChecker::CK_##name] = mgr.getCurrentCheckName(); \
  2301. }
  2302. REGISTER_CHECKER(MallocChecker)
  2303. REGISTER_CHECKER(NewDeleteChecker)
  2304. REGISTER_CHECKER(MismatchedDeallocatorChecker)