MallocChecker.cpp 93 KB

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