MallocChecker.cpp 97 KB

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