MallocChecker.cpp 100 KB

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