MallocChecker.cpp 86 KB

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