MallocChecker.cpp 59 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654
  1. //=== MallocChecker.cpp - A malloc/free checker -------------------*- C++ -*--//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. //
  10. // This file defines malloc/free checker, which checks for potential memory
  11. // leaks, double free, and use-after-free problems.
  12. //
  13. //===----------------------------------------------------------------------===//
  14. #include "ClangSACheckers.h"
  15. #include "InterCheckerAPI.h"
  16. #include "clang/AST/Attr.h"
  17. #include "clang/Basic/SourceManager.h"
  18. #include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
  19. #include "clang/StaticAnalyzer/Core/Checker.h"
  20. #include "clang/StaticAnalyzer/Core/CheckerManager.h"
  21. #include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h"
  22. #include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
  23. #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h"
  24. #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramStateTrait.h"
  25. #include "clang/StaticAnalyzer/Core/PathSensitive/SymbolManager.h"
  26. #include "llvm/ADT/ImmutableMap.h"
  27. #include "llvm/ADT/STLExtras.h"
  28. #include "llvm/ADT/SmallString.h"
  29. #include "llvm/ADT/StringExtras.h"
  30. #include <climits>
  31. using namespace clang;
  32. using namespace ento;
  33. namespace {
  34. class RefState {
  35. enum Kind { // Reference to allocated memory.
  36. Allocated,
  37. // Reference to released/freed memory.
  38. Released,
  39. // The responsibility for freeing resources has transfered from
  40. // this reference. A relinquished symbol should not be freed.
  41. Relinquished } K;
  42. const Stmt *S;
  43. public:
  44. RefState(Kind k, const Stmt *s) : K(k), S(s) {}
  45. bool isAllocated() const { return K == Allocated; }
  46. bool isReleased() const { return K == Released; }
  47. bool isRelinquished() const { return K == Relinquished; }
  48. const Stmt *getStmt() const { return S; }
  49. bool operator==(const RefState &X) const {
  50. return K == X.K && S == X.S;
  51. }
  52. static RefState getAllocated(const Stmt *s) {
  53. return RefState(Allocated, s);
  54. }
  55. static RefState getReleased(const Stmt *s) { return RefState(Released, s); }
  56. static RefState getRelinquished(const Stmt *s) {
  57. return RefState(Relinquished, s);
  58. }
  59. void Profile(llvm::FoldingSetNodeID &ID) const {
  60. ID.AddInteger(K);
  61. ID.AddPointer(S);
  62. }
  63. void dump(raw_ostream &OS) const {
  64. static const char *Table[] = {
  65. "Allocated",
  66. "Released",
  67. "Relinquished"
  68. };
  69. OS << Table[(unsigned) K];
  70. }
  71. LLVM_ATTRIBUTE_USED void dump() const {
  72. dump(llvm::errs());
  73. }
  74. };
  75. enum ReallocPairKind {
  76. RPToBeFreedAfterFailure,
  77. // The symbol has been freed when reallocation failed.
  78. RPIsFreeOnFailure,
  79. // The symbol does not need to be freed after reallocation fails.
  80. RPDoNotTrackAfterFailure
  81. };
  82. /// \class ReallocPair
  83. /// \brief Stores information about the symbol being reallocated by a call to
  84. /// 'realloc' to allow modeling failed reallocation later in the path.
  85. struct ReallocPair {
  86. // \brief The symbol which realloc reallocated.
  87. SymbolRef ReallocatedSym;
  88. ReallocPairKind Kind;
  89. ReallocPair(SymbolRef S, ReallocPairKind K) :
  90. ReallocatedSym(S), Kind(K) {}
  91. void Profile(llvm::FoldingSetNodeID &ID) const {
  92. ID.AddInteger(Kind);
  93. ID.AddPointer(ReallocatedSym);
  94. }
  95. bool operator==(const ReallocPair &X) const {
  96. return ReallocatedSym == X.ReallocatedSym &&
  97. Kind == X.Kind;
  98. }
  99. };
  100. typedef std::pair<const ExplodedNode*, const MemRegion*> LeakInfo;
  101. class MallocChecker : public Checker<check::DeadSymbols,
  102. check::PointerEscape,
  103. check::PreStmt<ReturnStmt>,
  104. check::PreStmt<CallExpr>,
  105. check::PostStmt<CallExpr>,
  106. check::PostStmt<BlockExpr>,
  107. check::PostObjCMessage,
  108. check::Location,
  109. eval::Assume>
  110. {
  111. mutable OwningPtr<BugType> BT_DoubleFree;
  112. mutable OwningPtr<BugType> BT_Leak;
  113. mutable OwningPtr<BugType> BT_UseFree;
  114. mutable OwningPtr<BugType> BT_BadFree;
  115. mutable OwningPtr<BugType> BT_OffsetFree;
  116. mutable IdentifierInfo *II_malloc, *II_free, *II_realloc, *II_calloc,
  117. *II_valloc, *II_reallocf, *II_strndup, *II_strdup;
  118. public:
  119. MallocChecker() : II_malloc(0), II_free(0), II_realloc(0), II_calloc(0),
  120. II_valloc(0), II_reallocf(0), II_strndup(0), II_strdup(0) {}
  121. /// In pessimistic mode, the checker assumes that it does not know which
  122. /// functions might free the memory.
  123. struct ChecksFilter {
  124. DefaultBool CMallocPessimistic;
  125. DefaultBool CMallocOptimistic;
  126. };
  127. ChecksFilter Filter;
  128. void checkPreStmt(const CallExpr *S, CheckerContext &C) const;
  129. void checkPostStmt(const CallExpr *CE, CheckerContext &C) const;
  130. void checkPostObjCMessage(const ObjCMethodCall &Call, CheckerContext &C) const;
  131. void checkPostStmt(const BlockExpr *BE, CheckerContext &C) const;
  132. void checkDeadSymbols(SymbolReaper &SymReaper, CheckerContext &C) const;
  133. void checkPreStmt(const ReturnStmt *S, CheckerContext &C) const;
  134. ProgramStateRef evalAssume(ProgramStateRef state, SVal Cond,
  135. bool Assumption) const;
  136. void checkLocation(SVal l, bool isLoad, const Stmt *S,
  137. CheckerContext &C) const;
  138. ProgramStateRef checkPointerEscape(ProgramStateRef State,
  139. const InvalidatedSymbols &Escaped,
  140. const CallEvent *Call,
  141. PointerEscapeKind Kind) const;
  142. void printState(raw_ostream &Out, ProgramStateRef State,
  143. const char *NL, const char *Sep) const;
  144. private:
  145. void initIdentifierInfo(ASTContext &C) const;
  146. /// Check if this is one of the functions which can allocate/reallocate memory
  147. /// pointed to by one of its arguments.
  148. bool isMemFunction(const FunctionDecl *FD, ASTContext &C) const;
  149. bool isFreeFunction(const FunctionDecl *FD, ASTContext &C) const;
  150. bool isAllocationFunction(const FunctionDecl *FD, ASTContext &C) const;
  151. static ProgramStateRef MallocMemReturnsAttr(CheckerContext &C,
  152. const CallExpr *CE,
  153. const OwnershipAttr* Att);
  154. static ProgramStateRef MallocMemAux(CheckerContext &C, const CallExpr *CE,
  155. const Expr *SizeEx, SVal Init,
  156. ProgramStateRef state) {
  157. return MallocMemAux(C, CE,
  158. state->getSVal(SizeEx, C.getLocationContext()),
  159. Init, state);
  160. }
  161. static ProgramStateRef MallocMemAux(CheckerContext &C, const CallExpr *CE,
  162. SVal SizeEx, SVal Init,
  163. ProgramStateRef state);
  164. /// Update the RefState to reflect the new memory allocation.
  165. static ProgramStateRef MallocUpdateRefState(CheckerContext &C,
  166. const CallExpr *CE,
  167. ProgramStateRef state);
  168. ProgramStateRef FreeMemAttr(CheckerContext &C, const CallExpr *CE,
  169. const OwnershipAttr* Att) const;
  170. ProgramStateRef FreeMemAux(CheckerContext &C, const CallExpr *CE,
  171. ProgramStateRef state, unsigned Num,
  172. bool Hold,
  173. bool &ReleasedAllocated,
  174. bool ReturnsNullOnFailure = false) const;
  175. ProgramStateRef FreeMemAux(CheckerContext &C, const Expr *Arg,
  176. const Expr *ParentExpr,
  177. ProgramStateRef State,
  178. bool Hold,
  179. bool &ReleasedAllocated,
  180. bool ReturnsNullOnFailure = false) const;
  181. ProgramStateRef ReallocMem(CheckerContext &C, const CallExpr *CE,
  182. bool FreesMemOnFailure) const;
  183. static ProgramStateRef CallocMem(CheckerContext &C, const CallExpr *CE);
  184. ///\brief Check if the memory associated with this symbol was released.
  185. bool isReleased(SymbolRef Sym, CheckerContext &C) const;
  186. bool checkUseAfterFree(SymbolRef Sym, CheckerContext &C,
  187. const Stmt *S = 0) const;
  188. /// Check if the function is not known to us. So, for example, we could
  189. /// conservatively assume it can free/reallocate it's pointer arguments.
  190. bool doesNotFreeMemory(const CallEvent *Call,
  191. ProgramStateRef State) const;
  192. static bool SummarizeValue(raw_ostream &os, SVal V);
  193. static bool SummarizeRegion(raw_ostream &os, const MemRegion *MR);
  194. void ReportBadFree(CheckerContext &C, SVal ArgVal, SourceRange range) const;
  195. void ReportOffsetFree(CheckerContext &C, SVal ArgVal, SourceRange Range)const;
  196. /// Find the location of the allocation for Sym on the path leading to the
  197. /// exploded node N.
  198. LeakInfo getAllocationSite(const ExplodedNode *N, SymbolRef Sym,
  199. CheckerContext &C) const;
  200. void reportLeak(SymbolRef Sym, ExplodedNode *N, CheckerContext &C) const;
  201. /// The bug visitor which allows us to print extra diagnostics along the
  202. /// BugReport path. For example, showing the allocation site of the leaked
  203. /// region.
  204. class MallocBugVisitor : public BugReporterVisitorImpl<MallocBugVisitor> {
  205. protected:
  206. enum NotificationMode {
  207. Normal,
  208. ReallocationFailed
  209. };
  210. // The allocated region symbol tracked by the main analysis.
  211. SymbolRef Sym;
  212. // The mode we are in, i.e. what kind of diagnostics will be emitted.
  213. NotificationMode Mode;
  214. // A symbol from when the primary region should have been reallocated.
  215. SymbolRef FailedReallocSymbol;
  216. bool IsLeak;
  217. public:
  218. MallocBugVisitor(SymbolRef S, bool isLeak = false)
  219. : Sym(S), Mode(Normal), FailedReallocSymbol(0), IsLeak(isLeak) {}
  220. virtual ~MallocBugVisitor() {}
  221. void Profile(llvm::FoldingSetNodeID &ID) const {
  222. static int X = 0;
  223. ID.AddPointer(&X);
  224. ID.AddPointer(Sym);
  225. }
  226. inline bool isAllocated(const RefState *S, const RefState *SPrev,
  227. const Stmt *Stmt) {
  228. // Did not track -> allocated. Other state (released) -> allocated.
  229. return (Stmt && isa<CallExpr>(Stmt) &&
  230. (S && S->isAllocated()) && (!SPrev || !SPrev->isAllocated()));
  231. }
  232. inline bool isReleased(const RefState *S, const RefState *SPrev,
  233. const Stmt *Stmt) {
  234. // Did not track -> released. Other state (allocated) -> released.
  235. return (Stmt && isa<CallExpr>(Stmt) &&
  236. (S && S->isReleased()) && (!SPrev || !SPrev->isReleased()));
  237. }
  238. inline bool isRelinquished(const RefState *S, const RefState *SPrev,
  239. const Stmt *Stmt) {
  240. // Did not track -> relinquished. Other state (allocated) -> relinquished.
  241. return (Stmt && (isa<CallExpr>(Stmt) || isa<ObjCMessageExpr>(Stmt) ||
  242. isa<ObjCPropertyRefExpr>(Stmt)) &&
  243. (S && S->isRelinquished()) &&
  244. (!SPrev || !SPrev->isRelinquished()));
  245. }
  246. inline bool isReallocFailedCheck(const RefState *S, const RefState *SPrev,
  247. const Stmt *Stmt) {
  248. // If the expression is not a call, and the state change is
  249. // released -> allocated, it must be the realloc return value
  250. // check. If we have to handle more cases here, it might be cleaner just
  251. // to track this extra bit in the state itself.
  252. return ((!Stmt || !isa<CallExpr>(Stmt)) &&
  253. (S && S->isAllocated()) && (SPrev && !SPrev->isAllocated()));
  254. }
  255. PathDiagnosticPiece *VisitNode(const ExplodedNode *N,
  256. const ExplodedNode *PrevN,
  257. BugReporterContext &BRC,
  258. BugReport &BR);
  259. PathDiagnosticPiece* getEndPath(BugReporterContext &BRC,
  260. const ExplodedNode *EndPathNode,
  261. BugReport &BR) {
  262. if (!IsLeak)
  263. return 0;
  264. PathDiagnosticLocation L =
  265. PathDiagnosticLocation::createEndOfPath(EndPathNode,
  266. BRC.getSourceManager());
  267. // Do not add the statement itself as a range in case of leak.
  268. return new PathDiagnosticEventPiece(L, BR.getDescription(), false);
  269. }
  270. private:
  271. class StackHintGeneratorForReallocationFailed
  272. : public StackHintGeneratorForSymbol {
  273. public:
  274. StackHintGeneratorForReallocationFailed(SymbolRef S, StringRef M)
  275. : StackHintGeneratorForSymbol(S, M) {}
  276. virtual std::string getMessageForArg(const Expr *ArgE, unsigned ArgIndex) {
  277. // Printed parameters start at 1, not 0.
  278. ++ArgIndex;
  279. SmallString<200> buf;
  280. llvm::raw_svector_ostream os(buf);
  281. os << "Reallocation of " << ArgIndex << llvm::getOrdinalSuffix(ArgIndex)
  282. << " parameter failed";
  283. return os.str();
  284. }
  285. virtual std::string getMessageForReturn(const CallExpr *CallExpr) {
  286. return "Reallocation of returned value failed";
  287. }
  288. };
  289. };
  290. };
  291. } // end anonymous namespace
  292. REGISTER_MAP_WITH_PROGRAMSTATE(RegionState, SymbolRef, RefState)
  293. REGISTER_MAP_WITH_PROGRAMSTATE(ReallocPairs, SymbolRef, ReallocPair)
  294. // A map from the freed symbol to the symbol representing the return value of
  295. // the free function.
  296. REGISTER_MAP_WITH_PROGRAMSTATE(FreeReturnValue, SymbolRef, SymbolRef)
  297. namespace {
  298. class StopTrackingCallback : public SymbolVisitor {
  299. ProgramStateRef state;
  300. public:
  301. StopTrackingCallback(ProgramStateRef st) : state(st) {}
  302. ProgramStateRef getState() const { return state; }
  303. bool VisitSymbol(SymbolRef sym) {
  304. state = state->remove<RegionState>(sym);
  305. return true;
  306. }
  307. };
  308. } // end anonymous namespace
  309. void MallocChecker::initIdentifierInfo(ASTContext &Ctx) const {
  310. if (II_malloc)
  311. return;
  312. II_malloc = &Ctx.Idents.get("malloc");
  313. II_free = &Ctx.Idents.get("free");
  314. II_realloc = &Ctx.Idents.get("realloc");
  315. II_reallocf = &Ctx.Idents.get("reallocf");
  316. II_calloc = &Ctx.Idents.get("calloc");
  317. II_valloc = &Ctx.Idents.get("valloc");
  318. II_strdup = &Ctx.Idents.get("strdup");
  319. II_strndup = &Ctx.Idents.get("strndup");
  320. }
  321. bool MallocChecker::isMemFunction(const FunctionDecl *FD, ASTContext &C) const {
  322. if (isFreeFunction(FD, C))
  323. return true;
  324. if (isAllocationFunction(FD, C))
  325. return true;
  326. return false;
  327. }
  328. bool MallocChecker::isAllocationFunction(const FunctionDecl *FD,
  329. ASTContext &C) const {
  330. if (!FD)
  331. return false;
  332. if (FD->getKind() == Decl::Function) {
  333. IdentifierInfo *FunI = FD->getIdentifier();
  334. initIdentifierInfo(C);
  335. if (FunI == II_malloc || FunI == II_realloc ||
  336. FunI == II_reallocf || FunI == II_calloc || FunI == II_valloc ||
  337. FunI == II_strdup || FunI == II_strndup)
  338. return true;
  339. }
  340. if (Filter.CMallocOptimistic && FD->hasAttrs())
  341. for (specific_attr_iterator<OwnershipAttr>
  342. i = FD->specific_attr_begin<OwnershipAttr>(),
  343. e = FD->specific_attr_end<OwnershipAttr>();
  344. i != e; ++i)
  345. if ((*i)->getOwnKind() == OwnershipAttr::Returns)
  346. return true;
  347. return false;
  348. }
  349. bool MallocChecker::isFreeFunction(const FunctionDecl *FD, ASTContext &C) const {
  350. if (!FD)
  351. return false;
  352. if (FD->getKind() == Decl::Function) {
  353. IdentifierInfo *FunI = FD->getIdentifier();
  354. initIdentifierInfo(C);
  355. if (FunI == II_free || FunI == II_realloc || FunI == II_reallocf)
  356. return true;
  357. }
  358. if (Filter.CMallocOptimistic && FD->hasAttrs())
  359. for (specific_attr_iterator<OwnershipAttr>
  360. i = FD->specific_attr_begin<OwnershipAttr>(),
  361. e = FD->specific_attr_end<OwnershipAttr>();
  362. i != e; ++i)
  363. if ((*i)->getOwnKind() == OwnershipAttr::Takes ||
  364. (*i)->getOwnKind() == OwnershipAttr::Holds)
  365. return true;
  366. return false;
  367. }
  368. void MallocChecker::checkPostStmt(const CallExpr *CE, CheckerContext &C) const {
  369. if (C.wasInlined)
  370. return;
  371. const FunctionDecl *FD = C.getCalleeDecl(CE);
  372. if (!FD)
  373. return;
  374. ProgramStateRef State = C.getState();
  375. bool ReleasedAllocatedMemory = false;
  376. if (FD->getKind() == Decl::Function) {
  377. initIdentifierInfo(C.getASTContext());
  378. IdentifierInfo *FunI = FD->getIdentifier();
  379. if (FunI == II_malloc || FunI == II_valloc) {
  380. if (CE->getNumArgs() < 1)
  381. return;
  382. State = MallocMemAux(C, CE, CE->getArg(0), UndefinedVal(), State);
  383. } else if (FunI == II_realloc) {
  384. State = ReallocMem(C, CE, false);
  385. } else if (FunI == II_reallocf) {
  386. State = ReallocMem(C, CE, true);
  387. } else if (FunI == II_calloc) {
  388. State = CallocMem(C, CE);
  389. } else if (FunI == II_free) {
  390. State = FreeMemAux(C, CE, State, 0, false, ReleasedAllocatedMemory);
  391. } else if (FunI == II_strdup) {
  392. State = MallocUpdateRefState(C, CE, State);
  393. } else if (FunI == II_strndup) {
  394. State = MallocUpdateRefState(C, CE, State);
  395. }
  396. }
  397. if (Filter.CMallocOptimistic) {
  398. // Check all the attributes, if there are any.
  399. // There can be multiple of these attributes.
  400. if (FD->hasAttrs())
  401. for (specific_attr_iterator<OwnershipAttr>
  402. i = FD->specific_attr_begin<OwnershipAttr>(),
  403. e = FD->specific_attr_end<OwnershipAttr>();
  404. i != e; ++i) {
  405. switch ((*i)->getOwnKind()) {
  406. case OwnershipAttr::Returns:
  407. State = MallocMemReturnsAttr(C, CE, *i);
  408. break;
  409. case OwnershipAttr::Takes:
  410. case OwnershipAttr::Holds:
  411. State = FreeMemAttr(C, CE, *i);
  412. break;
  413. }
  414. }
  415. }
  416. C.addTransition(State);
  417. }
  418. static bool isFreeWhenDoneSetToZero(const ObjCMethodCall &Call) {
  419. Selector S = Call.getSelector();
  420. for (unsigned i = 1; i < S.getNumArgs(); ++i)
  421. if (S.getNameForSlot(i).equals("freeWhenDone"))
  422. if (Call.getArgSVal(i).isConstant(0))
  423. return true;
  424. return false;
  425. }
  426. void MallocChecker::checkPostObjCMessage(const ObjCMethodCall &Call,
  427. CheckerContext &C) const {
  428. if (C.wasInlined)
  429. return;
  430. // If the first selector is dataWithBytesNoCopy, assume that the memory will
  431. // be released with 'free' by the new object.
  432. // Ex: [NSData dataWithBytesNoCopy:bytes length:10];
  433. // Unless 'freeWhenDone' param set to 0.
  434. // TODO: Check that the memory was allocated with malloc.
  435. bool ReleasedAllocatedMemory = false;
  436. Selector S = Call.getSelector();
  437. if ((S.getNameForSlot(0) == "dataWithBytesNoCopy" ||
  438. S.getNameForSlot(0) == "initWithBytesNoCopy" ||
  439. S.getNameForSlot(0) == "initWithCharactersNoCopy") &&
  440. !isFreeWhenDoneSetToZero(Call)){
  441. unsigned int argIdx = 0;
  442. ProgramStateRef State = FreeMemAux(C, Call.getArgExpr(argIdx),
  443. Call.getOriginExpr(), C.getState(), true,
  444. ReleasedAllocatedMemory,
  445. /* RetNullOnFailure*/ true);
  446. C.addTransition(State);
  447. }
  448. }
  449. ProgramStateRef MallocChecker::MallocMemReturnsAttr(CheckerContext &C,
  450. const CallExpr *CE,
  451. const OwnershipAttr* Att) {
  452. if (Att->getModule() != "malloc")
  453. return 0;
  454. OwnershipAttr::args_iterator I = Att->args_begin(), E = Att->args_end();
  455. if (I != E) {
  456. return MallocMemAux(C, CE, CE->getArg(*I), UndefinedVal(), C.getState());
  457. }
  458. return MallocMemAux(C, CE, UnknownVal(), UndefinedVal(), C.getState());
  459. }
  460. ProgramStateRef MallocChecker::MallocMemAux(CheckerContext &C,
  461. const CallExpr *CE,
  462. SVal Size, SVal Init,
  463. ProgramStateRef state) {
  464. // Bind the return value to the symbolic value from the heap region.
  465. // TODO: We could rewrite post visit to eval call; 'malloc' does not have
  466. // side effects other than what we model here.
  467. unsigned Count = C.blockCount();
  468. SValBuilder &svalBuilder = C.getSValBuilder();
  469. const LocationContext *LCtx = C.getPredecessor()->getLocationContext();
  470. DefinedSVal RetVal = svalBuilder.getConjuredHeapSymbolVal(CE, LCtx, Count)
  471. .castAs<DefinedSVal>();
  472. state = state->BindExpr(CE, C.getLocationContext(), RetVal);
  473. // We expect the malloc functions to return a pointer.
  474. if (!RetVal.getAs<Loc>())
  475. return 0;
  476. // Fill the region with the initialization value.
  477. state = state->bindDefault(RetVal, Init);
  478. // Set the region's extent equal to the Size parameter.
  479. const SymbolicRegion *R =
  480. dyn_cast_or_null<SymbolicRegion>(RetVal.getAsRegion());
  481. if (!R)
  482. return 0;
  483. if (Optional<DefinedOrUnknownSVal> DefinedSize =
  484. Size.getAs<DefinedOrUnknownSVal>()) {
  485. SValBuilder &svalBuilder = C.getSValBuilder();
  486. DefinedOrUnknownSVal Extent = R->getExtent(svalBuilder);
  487. DefinedOrUnknownSVal extentMatchesSize =
  488. svalBuilder.evalEQ(state, Extent, *DefinedSize);
  489. state = state->assume(extentMatchesSize, true);
  490. assert(state);
  491. }
  492. return MallocUpdateRefState(C, CE, state);
  493. }
  494. ProgramStateRef MallocChecker::MallocUpdateRefState(CheckerContext &C,
  495. const CallExpr *CE,
  496. ProgramStateRef state) {
  497. // Get the return value.
  498. SVal retVal = state->getSVal(CE, C.getLocationContext());
  499. // We expect the malloc functions to return a pointer.
  500. if (!retVal.getAs<Loc>())
  501. return 0;
  502. SymbolRef Sym = retVal.getAsLocSymbol();
  503. assert(Sym);
  504. // Set the symbol's state to Allocated.
  505. return state->set<RegionState>(Sym, RefState::getAllocated(CE));
  506. }
  507. ProgramStateRef MallocChecker::FreeMemAttr(CheckerContext &C,
  508. const CallExpr *CE,
  509. const OwnershipAttr* Att) const {
  510. if (Att->getModule() != "malloc")
  511. return 0;
  512. ProgramStateRef State = C.getState();
  513. bool ReleasedAllocated = false;
  514. for (OwnershipAttr::args_iterator I = Att->args_begin(), E = Att->args_end();
  515. I != E; ++I) {
  516. ProgramStateRef StateI = FreeMemAux(C, CE, State, *I,
  517. Att->getOwnKind() == OwnershipAttr::Holds,
  518. ReleasedAllocated);
  519. if (StateI)
  520. State = StateI;
  521. }
  522. return State;
  523. }
  524. ProgramStateRef MallocChecker::FreeMemAux(CheckerContext &C,
  525. const CallExpr *CE,
  526. ProgramStateRef state,
  527. unsigned Num,
  528. bool Hold,
  529. bool &ReleasedAllocated,
  530. bool ReturnsNullOnFailure) const {
  531. if (CE->getNumArgs() < (Num + 1))
  532. return 0;
  533. return FreeMemAux(C, CE->getArg(Num), CE, state, Hold,
  534. ReleasedAllocated, ReturnsNullOnFailure);
  535. }
  536. /// Checks if the previous call to free on the given symbol failed - if free
  537. /// failed, returns true. Also, returns the corresponding return value symbol.
  538. static bool didPreviousFreeFail(ProgramStateRef State,
  539. SymbolRef Sym, SymbolRef &RetStatusSymbol) {
  540. const SymbolRef *Ret = State->get<FreeReturnValue>(Sym);
  541. if (Ret) {
  542. assert(*Ret && "We should not store the null return symbol");
  543. ConstraintManager &CMgr = State->getConstraintManager();
  544. ConditionTruthVal FreeFailed = CMgr.isNull(State, *Ret);
  545. RetStatusSymbol = *Ret;
  546. return FreeFailed.isConstrainedTrue();
  547. }
  548. return false;
  549. }
  550. ProgramStateRef MallocChecker::FreeMemAux(CheckerContext &C,
  551. const Expr *ArgExpr,
  552. const Expr *ParentExpr,
  553. ProgramStateRef State,
  554. bool Hold,
  555. bool &ReleasedAllocated,
  556. bool ReturnsNullOnFailure) const {
  557. SVal ArgVal = State->getSVal(ArgExpr, C.getLocationContext());
  558. if (!ArgVal.getAs<DefinedOrUnknownSVal>())
  559. return 0;
  560. DefinedOrUnknownSVal location = ArgVal.castAs<DefinedOrUnknownSVal>();
  561. // Check for null dereferences.
  562. if (!location.getAs<Loc>())
  563. return 0;
  564. // The explicit NULL case, no operation is performed.
  565. ProgramStateRef notNullState, nullState;
  566. llvm::tie(notNullState, nullState) = State->assume(location);
  567. if (nullState && !notNullState)
  568. return 0;
  569. // Unknown values could easily be okay
  570. // Undefined values are handled elsewhere
  571. if (ArgVal.isUnknownOrUndef())
  572. return 0;
  573. const MemRegion *R = ArgVal.getAsRegion();
  574. // Nonlocs can't be freed, of course.
  575. // Non-region locations (labels and fixed addresses) also shouldn't be freed.
  576. if (!R) {
  577. ReportBadFree(C, ArgVal, ArgExpr->getSourceRange());
  578. return 0;
  579. }
  580. R = R->StripCasts();
  581. // Blocks might show up as heap data, but should not be free()d
  582. if (isa<BlockDataRegion>(R)) {
  583. ReportBadFree(C, ArgVal, ArgExpr->getSourceRange());
  584. return 0;
  585. }
  586. const MemSpaceRegion *MS = R->getMemorySpace();
  587. // Parameters, locals, statics, and globals shouldn't be freed.
  588. if (!(isa<UnknownSpaceRegion>(MS) || isa<HeapSpaceRegion>(MS))) {
  589. // FIXME: at the time this code was written, malloc() regions were
  590. // represented by conjured symbols, which are all in UnknownSpaceRegion.
  591. // This means that there isn't actually anything from HeapSpaceRegion
  592. // that should be freed, even though we allow it here.
  593. // Of course, free() can work on memory allocated outside the current
  594. // function, so UnknownSpaceRegion is always a possibility.
  595. // False negatives are better than false positives.
  596. ReportBadFree(C, ArgVal, ArgExpr->getSourceRange());
  597. return 0;
  598. }
  599. const SymbolicRegion *SrBase = dyn_cast<SymbolicRegion>(R->getBaseRegion());
  600. // Various cases could lead to non-symbol values here.
  601. // For now, ignore them.
  602. if (!SrBase)
  603. return 0;
  604. SymbolRef SymBase = SrBase->getSymbol();
  605. const RefState *RsBase = State->get<RegionState>(SymBase);
  606. SymbolRef PreviousRetStatusSymbol = 0;
  607. // Check double free.
  608. if (RsBase &&
  609. (RsBase->isReleased() || RsBase->isRelinquished()) &&
  610. !didPreviousFreeFail(State, SymBase, PreviousRetStatusSymbol)) {
  611. if (ExplodedNode *N = C.generateSink()) {
  612. if (!BT_DoubleFree)
  613. BT_DoubleFree.reset(
  614. new BugType("Double free", "Memory Error"));
  615. BugReport *R = new BugReport(*BT_DoubleFree,
  616. (RsBase->isReleased() ? "Attempt to free released memory"
  617. : "Attempt to free non-owned memory"),
  618. N);
  619. R->addRange(ArgExpr->getSourceRange());
  620. R->markInteresting(SymBase);
  621. if (PreviousRetStatusSymbol)
  622. R->markInteresting(PreviousRetStatusSymbol);
  623. R->addVisitor(new MallocBugVisitor(SymBase));
  624. C.emitReport(R);
  625. }
  626. return 0;
  627. }
  628. // Check if the memory location being freed is the actual location
  629. // allocated, or an offset.
  630. RegionOffset Offset = R->getAsOffset();
  631. if (RsBase && RsBase->isAllocated() &&
  632. Offset.isValid() &&
  633. !Offset.hasSymbolicOffset() &&
  634. Offset.getOffset() != 0) {
  635. ReportOffsetFree(C, ArgVal, ArgExpr->getSourceRange());
  636. return 0;
  637. }
  638. ReleasedAllocated = (RsBase != 0);
  639. // Clean out the info on previous call to free return info.
  640. State = State->remove<FreeReturnValue>(SymBase);
  641. // Keep track of the return value. If it is NULL, we will know that free
  642. // failed.
  643. if (ReturnsNullOnFailure) {
  644. SVal RetVal = C.getSVal(ParentExpr);
  645. SymbolRef RetStatusSymbol = RetVal.getAsSymbol();
  646. if (RetStatusSymbol) {
  647. C.getSymbolManager().addSymbolDependency(SymBase, RetStatusSymbol);
  648. State = State->set<FreeReturnValue>(SymBase, RetStatusSymbol);
  649. }
  650. }
  651. // Normal free.
  652. if (Hold) {
  653. return State->set<RegionState>(SymBase,
  654. RefState::getRelinquished(ParentExpr));
  655. }
  656. return State->set<RegionState>(SymBase, RefState::getReleased(ParentExpr));
  657. }
  658. bool MallocChecker::SummarizeValue(raw_ostream &os, SVal V) {
  659. if (Optional<nonloc::ConcreteInt> IntVal = V.getAs<nonloc::ConcreteInt>())
  660. os << "an integer (" << IntVal->getValue() << ")";
  661. else if (Optional<loc::ConcreteInt> ConstAddr = V.getAs<loc::ConcreteInt>())
  662. os << "a constant address (" << ConstAddr->getValue() << ")";
  663. else if (Optional<loc::GotoLabel> Label = V.getAs<loc::GotoLabel>())
  664. os << "the address of the label '" << Label->getLabel()->getName() << "'";
  665. else
  666. return false;
  667. return true;
  668. }
  669. bool MallocChecker::SummarizeRegion(raw_ostream &os,
  670. const MemRegion *MR) {
  671. switch (MR->getKind()) {
  672. case MemRegion::FunctionTextRegionKind: {
  673. const NamedDecl *FD = cast<FunctionTextRegion>(MR)->getDecl();
  674. if (FD)
  675. os << "the address of the function '" << *FD << '\'';
  676. else
  677. os << "the address of a function";
  678. return true;
  679. }
  680. case MemRegion::BlockTextRegionKind:
  681. os << "block text";
  682. return true;
  683. case MemRegion::BlockDataRegionKind:
  684. // FIXME: where the block came from?
  685. os << "a block";
  686. return true;
  687. default: {
  688. const MemSpaceRegion *MS = MR->getMemorySpace();
  689. if (isa<StackLocalsSpaceRegion>(MS)) {
  690. const VarRegion *VR = dyn_cast<VarRegion>(MR);
  691. const VarDecl *VD;
  692. if (VR)
  693. VD = VR->getDecl();
  694. else
  695. VD = NULL;
  696. if (VD)
  697. os << "the address of the local variable '" << VD->getName() << "'";
  698. else
  699. os << "the address of a local stack variable";
  700. return true;
  701. }
  702. if (isa<StackArgumentsSpaceRegion>(MS)) {
  703. const VarRegion *VR = dyn_cast<VarRegion>(MR);
  704. const VarDecl *VD;
  705. if (VR)
  706. VD = VR->getDecl();
  707. else
  708. VD = NULL;
  709. if (VD)
  710. os << "the address of the parameter '" << VD->getName() << "'";
  711. else
  712. os << "the address of a parameter";
  713. return true;
  714. }
  715. if (isa<GlobalsSpaceRegion>(MS)) {
  716. const VarRegion *VR = dyn_cast<VarRegion>(MR);
  717. const VarDecl *VD;
  718. if (VR)
  719. VD = VR->getDecl();
  720. else
  721. VD = NULL;
  722. if (VD) {
  723. if (VD->isStaticLocal())
  724. os << "the address of the static variable '" << VD->getName() << "'";
  725. else
  726. os << "the address of the global variable '" << VD->getName() << "'";
  727. } else
  728. os << "the address of a global variable";
  729. return true;
  730. }
  731. return false;
  732. }
  733. }
  734. }
  735. void MallocChecker::ReportBadFree(CheckerContext &C, SVal ArgVal,
  736. SourceRange range) const {
  737. if (ExplodedNode *N = C.generateSink()) {
  738. if (!BT_BadFree)
  739. BT_BadFree.reset(new BugType("Bad free", "Memory Error"));
  740. SmallString<100> buf;
  741. llvm::raw_svector_ostream os(buf);
  742. const MemRegion *MR = ArgVal.getAsRegion();
  743. if (MR) {
  744. while (const ElementRegion *ER = dyn_cast<ElementRegion>(MR))
  745. MR = ER->getSuperRegion();
  746. // Special case for alloca()
  747. if (isa<AllocaRegion>(MR))
  748. os << "Argument to free() was allocated by alloca(), not malloc()";
  749. else {
  750. os << "Argument to free() is ";
  751. if (SummarizeRegion(os, MR))
  752. os << ", which is not memory allocated by malloc()";
  753. else
  754. os << "not memory allocated by malloc()";
  755. }
  756. } else {
  757. os << "Argument to free() is ";
  758. if (SummarizeValue(os, ArgVal))
  759. os << ", which is not memory allocated by malloc()";
  760. else
  761. os << "not memory allocated by malloc()";
  762. }
  763. BugReport *R = new BugReport(*BT_BadFree, os.str(), N);
  764. R->markInteresting(MR);
  765. R->addRange(range);
  766. C.emitReport(R);
  767. }
  768. }
  769. void MallocChecker::ReportOffsetFree(CheckerContext &C, SVal ArgVal,
  770. SourceRange Range) const {
  771. ExplodedNode *N = C.generateSink();
  772. if (N == NULL)
  773. return;
  774. if (!BT_OffsetFree)
  775. BT_OffsetFree.reset(new BugType("Offset free", "Memory Error"));
  776. SmallString<100> buf;
  777. llvm::raw_svector_ostream os(buf);
  778. const MemRegion *MR = ArgVal.getAsRegion();
  779. assert(MR && "Only MemRegion based symbols can have offset free errors");
  780. RegionOffset Offset = MR->getAsOffset();
  781. assert((Offset.isValid() &&
  782. !Offset.hasSymbolicOffset() &&
  783. Offset.getOffset() != 0) &&
  784. "Only symbols with a valid offset can have offset free errors");
  785. int offsetBytes = Offset.getOffset() / C.getASTContext().getCharWidth();
  786. os << "Argument to free() is offset by "
  787. << offsetBytes
  788. << " "
  789. << ((abs(offsetBytes) > 1) ? "bytes" : "byte")
  790. << " from the start of memory allocated by malloc()";
  791. BugReport *R = new BugReport(*BT_OffsetFree, os.str(), N);
  792. R->markInteresting(MR->getBaseRegion());
  793. R->addRange(Range);
  794. C.emitReport(R);
  795. }
  796. ProgramStateRef MallocChecker::ReallocMem(CheckerContext &C,
  797. const CallExpr *CE,
  798. bool FreesOnFail) const {
  799. if (CE->getNumArgs() < 2)
  800. return 0;
  801. ProgramStateRef state = C.getState();
  802. const Expr *arg0Expr = CE->getArg(0);
  803. const LocationContext *LCtx = C.getLocationContext();
  804. SVal Arg0Val = state->getSVal(arg0Expr, LCtx);
  805. if (!Arg0Val.getAs<DefinedOrUnknownSVal>())
  806. return 0;
  807. DefinedOrUnknownSVal arg0Val = Arg0Val.castAs<DefinedOrUnknownSVal>();
  808. SValBuilder &svalBuilder = C.getSValBuilder();
  809. DefinedOrUnknownSVal PtrEQ =
  810. svalBuilder.evalEQ(state, arg0Val, svalBuilder.makeNull());
  811. // Get the size argument. If there is no size arg then give up.
  812. const Expr *Arg1 = CE->getArg(1);
  813. if (!Arg1)
  814. return 0;
  815. // Get the value of the size argument.
  816. SVal Arg1ValG = state->getSVal(Arg1, LCtx);
  817. if (!Arg1ValG.getAs<DefinedOrUnknownSVal>())
  818. return 0;
  819. DefinedOrUnknownSVal Arg1Val = Arg1ValG.castAs<DefinedOrUnknownSVal>();
  820. // Compare the size argument to 0.
  821. DefinedOrUnknownSVal SizeZero =
  822. svalBuilder.evalEQ(state, Arg1Val,
  823. svalBuilder.makeIntValWithPtrWidth(0, false));
  824. ProgramStateRef StatePtrIsNull, StatePtrNotNull;
  825. llvm::tie(StatePtrIsNull, StatePtrNotNull) = state->assume(PtrEQ);
  826. ProgramStateRef StateSizeIsZero, StateSizeNotZero;
  827. llvm::tie(StateSizeIsZero, StateSizeNotZero) = state->assume(SizeZero);
  828. // We only assume exceptional states if they are definitely true; if the
  829. // state is under-constrained, assume regular realloc behavior.
  830. bool PrtIsNull = StatePtrIsNull && !StatePtrNotNull;
  831. bool SizeIsZero = StateSizeIsZero && !StateSizeNotZero;
  832. // If the ptr is NULL and the size is not 0, the call is equivalent to
  833. // malloc(size).
  834. if ( PrtIsNull && !SizeIsZero) {
  835. ProgramStateRef stateMalloc = MallocMemAux(C, CE, CE->getArg(1),
  836. UndefinedVal(), StatePtrIsNull);
  837. return stateMalloc;
  838. }
  839. if (PrtIsNull && SizeIsZero)
  840. return 0;
  841. // Get the from and to pointer symbols as in toPtr = realloc(fromPtr, size).
  842. assert(!PrtIsNull);
  843. SymbolRef FromPtr = arg0Val.getAsSymbol();
  844. SVal RetVal = state->getSVal(CE, LCtx);
  845. SymbolRef ToPtr = RetVal.getAsSymbol();
  846. if (!FromPtr || !ToPtr)
  847. return 0;
  848. bool ReleasedAllocated = false;
  849. // If the size is 0, free the memory.
  850. if (SizeIsZero)
  851. if (ProgramStateRef stateFree = FreeMemAux(C, CE, StateSizeIsZero, 0,
  852. false, ReleasedAllocated)){
  853. // The semantics of the return value are:
  854. // If size was equal to 0, either NULL or a pointer suitable to be passed
  855. // to free() is returned. We just free the input pointer and do not add
  856. // any constrains on the output pointer.
  857. return stateFree;
  858. }
  859. // Default behavior.
  860. if (ProgramStateRef stateFree =
  861. FreeMemAux(C, CE, state, 0, false, ReleasedAllocated)) {
  862. ProgramStateRef stateRealloc = MallocMemAux(C, CE, CE->getArg(1),
  863. UnknownVal(), stateFree);
  864. if (!stateRealloc)
  865. return 0;
  866. ReallocPairKind Kind = RPToBeFreedAfterFailure;
  867. if (FreesOnFail)
  868. Kind = RPIsFreeOnFailure;
  869. else if (!ReleasedAllocated)
  870. Kind = RPDoNotTrackAfterFailure;
  871. // Record the info about the reallocated symbol so that we could properly
  872. // process failed reallocation.
  873. stateRealloc = stateRealloc->set<ReallocPairs>(ToPtr,
  874. ReallocPair(FromPtr, Kind));
  875. // The reallocated symbol should stay alive for as long as the new symbol.
  876. C.getSymbolManager().addSymbolDependency(ToPtr, FromPtr);
  877. return stateRealloc;
  878. }
  879. return 0;
  880. }
  881. ProgramStateRef MallocChecker::CallocMem(CheckerContext &C, const CallExpr *CE){
  882. if (CE->getNumArgs() < 2)
  883. return 0;
  884. ProgramStateRef state = C.getState();
  885. SValBuilder &svalBuilder = C.getSValBuilder();
  886. const LocationContext *LCtx = C.getLocationContext();
  887. SVal count = state->getSVal(CE->getArg(0), LCtx);
  888. SVal elementSize = state->getSVal(CE->getArg(1), LCtx);
  889. SVal TotalSize = svalBuilder.evalBinOp(state, BO_Mul, count, elementSize,
  890. svalBuilder.getContext().getSizeType());
  891. SVal zeroVal = svalBuilder.makeZeroVal(svalBuilder.getContext().CharTy);
  892. return MallocMemAux(C, CE, TotalSize, zeroVal, state);
  893. }
  894. LeakInfo
  895. MallocChecker::getAllocationSite(const ExplodedNode *N, SymbolRef Sym,
  896. CheckerContext &C) const {
  897. const LocationContext *LeakContext = N->getLocationContext();
  898. // Walk the ExplodedGraph backwards and find the first node that referred to
  899. // the tracked symbol.
  900. const ExplodedNode *AllocNode = N;
  901. const MemRegion *ReferenceRegion = 0;
  902. while (N) {
  903. ProgramStateRef State = N->getState();
  904. if (!State->get<RegionState>(Sym))
  905. break;
  906. // Find the most recent expression bound to the symbol in the current
  907. // context.
  908. if (!ReferenceRegion) {
  909. if (const MemRegion *MR = C.getLocationRegionIfPostStore(N)) {
  910. SVal Val = State->getSVal(MR);
  911. if (Val.getAsLocSymbol() == Sym)
  912. ReferenceRegion = MR;
  913. }
  914. }
  915. // Allocation node, is the last node in the current context in which the
  916. // symbol was tracked.
  917. if (N->getLocationContext() == LeakContext)
  918. AllocNode = N;
  919. N = N->pred_empty() ? NULL : *(N->pred_begin());
  920. }
  921. return LeakInfo(AllocNode, ReferenceRegion);
  922. }
  923. void MallocChecker::reportLeak(SymbolRef Sym, ExplodedNode *N,
  924. CheckerContext &C) const {
  925. assert(N);
  926. if (!BT_Leak) {
  927. BT_Leak.reset(new BugType("Memory leak", "Memory Error"));
  928. // Leaks should not be reported if they are post-dominated by a sink:
  929. // (1) Sinks are higher importance bugs.
  930. // (2) NoReturnFunctionChecker uses sink nodes to represent paths ending
  931. // with __noreturn functions such as assert() or exit(). We choose not
  932. // to report leaks on such paths.
  933. BT_Leak->setSuppressOnSink(true);
  934. }
  935. // Most bug reports are cached at the location where they occurred.
  936. // With leaks, we want to unique them by the location where they were
  937. // allocated, and only report a single path.
  938. PathDiagnosticLocation LocUsedForUniqueing;
  939. const ExplodedNode *AllocNode = 0;
  940. const MemRegion *Region = 0;
  941. llvm::tie(AllocNode, Region) = getAllocationSite(N, Sym, C);
  942. ProgramPoint P = AllocNode->getLocation();
  943. const Stmt *AllocationStmt = 0;
  944. if (CallExitEnd *Exit = dyn_cast<CallExitEnd>(&P))
  945. AllocationStmt = Exit->getCalleeContext()->getCallSite();
  946. else if (StmtPoint *SP = dyn_cast<StmtPoint>(&P))
  947. AllocationStmt = SP->getStmt();
  948. if (AllocationStmt)
  949. LocUsedForUniqueing = PathDiagnosticLocation::createBegin(AllocationStmt,
  950. C.getSourceManager(),
  951. AllocNode->getLocationContext());
  952. SmallString<200> buf;
  953. llvm::raw_svector_ostream os(buf);
  954. os << "Memory is never released; potential leak";
  955. if (Region && Region->canPrintPretty()) {
  956. os << " of memory pointed to by '";
  957. Region->printPretty(os);
  958. os << '\'';
  959. }
  960. BugReport *R = new BugReport(*BT_Leak, os.str(), N,
  961. LocUsedForUniqueing,
  962. AllocNode->getLocationContext()->getDecl());
  963. R->markInteresting(Sym);
  964. R->addVisitor(new MallocBugVisitor(Sym, true));
  965. C.emitReport(R);
  966. }
  967. void MallocChecker::checkDeadSymbols(SymbolReaper &SymReaper,
  968. CheckerContext &C) const
  969. {
  970. if (!SymReaper.hasDeadSymbols())
  971. return;
  972. ProgramStateRef state = C.getState();
  973. RegionStateTy RS = state->get<RegionState>();
  974. RegionStateTy::Factory &F = state->get_context<RegionState>();
  975. SmallVector<SymbolRef, 2> Errors;
  976. for (RegionStateTy::iterator I = RS.begin(), E = RS.end(); I != E; ++I) {
  977. if (SymReaper.isDead(I->first)) {
  978. if (I->second.isAllocated())
  979. Errors.push_back(I->first);
  980. // Remove the dead symbol from the map.
  981. RS = F.remove(RS, I->first);
  982. }
  983. }
  984. // Cleanup the Realloc Pairs Map.
  985. ReallocPairsTy RP = state->get<ReallocPairs>();
  986. for (ReallocPairsTy::iterator I = RP.begin(), E = RP.end(); I != E; ++I) {
  987. if (SymReaper.isDead(I->first) ||
  988. SymReaper.isDead(I->second.ReallocatedSym)) {
  989. state = state->remove<ReallocPairs>(I->first);
  990. }
  991. }
  992. // Cleanup the FreeReturnValue Map.
  993. FreeReturnValueTy FR = state->get<FreeReturnValue>();
  994. for (FreeReturnValueTy::iterator I = FR.begin(), E = FR.end(); I != E; ++I) {
  995. if (SymReaper.isDead(I->first) ||
  996. SymReaper.isDead(I->second)) {
  997. state = state->remove<FreeReturnValue>(I->first);
  998. }
  999. }
  1000. // Generate leak node.
  1001. ExplodedNode *N = C.getPredecessor();
  1002. if (!Errors.empty()) {
  1003. static SimpleProgramPointTag Tag("MallocChecker : DeadSymbolsLeak");
  1004. N = C.addTransition(C.getState(), C.getPredecessor(), &Tag);
  1005. for (SmallVector<SymbolRef, 2>::iterator
  1006. I = Errors.begin(), E = Errors.end(); I != E; ++I) {
  1007. reportLeak(*I, N, C);
  1008. }
  1009. }
  1010. C.addTransition(state->set<RegionState>(RS), N);
  1011. }
  1012. void MallocChecker::checkPreStmt(const CallExpr *CE, CheckerContext &C) const {
  1013. // We will check for double free in the post visit.
  1014. if (isFreeFunction(C.getCalleeDecl(CE), C.getASTContext()))
  1015. return;
  1016. // Check use after free, when a freed pointer is passed to a call.
  1017. ProgramStateRef State = C.getState();
  1018. for (CallExpr::const_arg_iterator I = CE->arg_begin(),
  1019. E = CE->arg_end(); I != E; ++I) {
  1020. const Expr *A = *I;
  1021. if (A->getType().getTypePtr()->isAnyPointerType()) {
  1022. SymbolRef Sym = State->getSVal(A, C.getLocationContext()).getAsSymbol();
  1023. if (!Sym)
  1024. continue;
  1025. if (checkUseAfterFree(Sym, C, A))
  1026. return;
  1027. }
  1028. }
  1029. }
  1030. void MallocChecker::checkPreStmt(const ReturnStmt *S, CheckerContext &C) const {
  1031. const Expr *E = S->getRetValue();
  1032. if (!E)
  1033. return;
  1034. // Check if we are returning a symbol.
  1035. ProgramStateRef State = C.getState();
  1036. SVal RetVal = State->getSVal(E, C.getLocationContext());
  1037. SymbolRef Sym = RetVal.getAsSymbol();
  1038. if (!Sym)
  1039. // If we are returning a field of the allocated struct or an array element,
  1040. // the callee could still free the memory.
  1041. // TODO: This logic should be a part of generic symbol escape callback.
  1042. if (const MemRegion *MR = RetVal.getAsRegion())
  1043. if (isa<FieldRegion>(MR) || isa<ElementRegion>(MR))
  1044. if (const SymbolicRegion *BMR =
  1045. dyn_cast<SymbolicRegion>(MR->getBaseRegion()))
  1046. Sym = BMR->getSymbol();
  1047. // Check if we are returning freed memory.
  1048. if (Sym)
  1049. checkUseAfterFree(Sym, C, E);
  1050. }
  1051. // TODO: Blocks should be either inlined or should call invalidate regions
  1052. // upon invocation. After that's in place, special casing here will not be
  1053. // needed.
  1054. void MallocChecker::checkPostStmt(const BlockExpr *BE,
  1055. CheckerContext &C) const {
  1056. // Scan the BlockDecRefExprs for any object the retain count checker
  1057. // may be tracking.
  1058. if (!BE->getBlockDecl()->hasCaptures())
  1059. return;
  1060. ProgramStateRef state = C.getState();
  1061. const BlockDataRegion *R =
  1062. cast<BlockDataRegion>(state->getSVal(BE,
  1063. C.getLocationContext()).getAsRegion());
  1064. BlockDataRegion::referenced_vars_iterator I = R->referenced_vars_begin(),
  1065. E = R->referenced_vars_end();
  1066. if (I == E)
  1067. return;
  1068. SmallVector<const MemRegion*, 10> Regions;
  1069. const LocationContext *LC = C.getLocationContext();
  1070. MemRegionManager &MemMgr = C.getSValBuilder().getRegionManager();
  1071. for ( ; I != E; ++I) {
  1072. const VarRegion *VR = I.getCapturedRegion();
  1073. if (VR->getSuperRegion() == R) {
  1074. VR = MemMgr.getVarRegion(VR->getDecl(), LC);
  1075. }
  1076. Regions.push_back(VR);
  1077. }
  1078. state =
  1079. state->scanReachableSymbols<StopTrackingCallback>(Regions.data(),
  1080. Regions.data() + Regions.size()).getState();
  1081. C.addTransition(state);
  1082. }
  1083. bool MallocChecker::isReleased(SymbolRef Sym, CheckerContext &C) const {
  1084. assert(Sym);
  1085. const RefState *RS = C.getState()->get<RegionState>(Sym);
  1086. return (RS && RS->isReleased());
  1087. }
  1088. bool MallocChecker::checkUseAfterFree(SymbolRef Sym, CheckerContext &C,
  1089. const Stmt *S) const {
  1090. if (isReleased(Sym, C)) {
  1091. if (ExplodedNode *N = C.generateSink()) {
  1092. if (!BT_UseFree)
  1093. BT_UseFree.reset(new BugType("Use-after-free", "Memory Error"));
  1094. BugReport *R = new BugReport(*BT_UseFree,
  1095. "Use of memory after it is freed",N);
  1096. if (S)
  1097. R->addRange(S->getSourceRange());
  1098. R->markInteresting(Sym);
  1099. R->addVisitor(new MallocBugVisitor(Sym));
  1100. C.emitReport(R);
  1101. return true;
  1102. }
  1103. }
  1104. return false;
  1105. }
  1106. // Check if the location is a freed symbolic region.
  1107. void MallocChecker::checkLocation(SVal l, bool isLoad, const Stmt *S,
  1108. CheckerContext &C) const {
  1109. SymbolRef Sym = l.getLocSymbolInBase();
  1110. if (Sym)
  1111. checkUseAfterFree(Sym, C, S);
  1112. }
  1113. // If a symbolic region is assumed to NULL (or another constant), stop tracking
  1114. // it - assuming that allocation failed on this path.
  1115. ProgramStateRef MallocChecker::evalAssume(ProgramStateRef state,
  1116. SVal Cond,
  1117. bool Assumption) const {
  1118. RegionStateTy RS = state->get<RegionState>();
  1119. for (RegionStateTy::iterator I = RS.begin(), E = RS.end(); I != E; ++I) {
  1120. // If the symbol is assumed to be NULL, remove it from consideration.
  1121. ConstraintManager &CMgr = state->getConstraintManager();
  1122. ConditionTruthVal AllocFailed = CMgr.isNull(state, I.getKey());
  1123. if (AllocFailed.isConstrainedTrue())
  1124. state = state->remove<RegionState>(I.getKey());
  1125. }
  1126. // Realloc returns 0 when reallocation fails, which means that we should
  1127. // restore the state of the pointer being reallocated.
  1128. ReallocPairsTy RP = state->get<ReallocPairs>();
  1129. for (ReallocPairsTy::iterator I = RP.begin(), E = RP.end(); I != E; ++I) {
  1130. // If the symbol is assumed to be NULL, remove it from consideration.
  1131. ConstraintManager &CMgr = state->getConstraintManager();
  1132. ConditionTruthVal AllocFailed = CMgr.isNull(state, I.getKey());
  1133. if (!AllocFailed.isConstrainedTrue())
  1134. continue;
  1135. SymbolRef ReallocSym = I.getData().ReallocatedSym;
  1136. if (const RefState *RS = state->get<RegionState>(ReallocSym)) {
  1137. if (RS->isReleased()) {
  1138. if (I.getData().Kind == RPToBeFreedAfterFailure)
  1139. state = state->set<RegionState>(ReallocSym,
  1140. RefState::getAllocated(RS->getStmt()));
  1141. else if (I.getData().Kind == RPDoNotTrackAfterFailure)
  1142. state = state->remove<RegionState>(ReallocSym);
  1143. else
  1144. assert(I.getData().Kind == RPIsFreeOnFailure);
  1145. }
  1146. }
  1147. state = state->remove<ReallocPairs>(I.getKey());
  1148. }
  1149. return state;
  1150. }
  1151. // Check if the function is known to us. So, for example, we could
  1152. // conservatively assume it can free/reallocate its pointer arguments.
  1153. // (We assume that the pointers cannot escape through calls to system
  1154. // functions not handled by this checker.)
  1155. bool MallocChecker::doesNotFreeMemory(const CallEvent *Call,
  1156. ProgramStateRef State) const {
  1157. assert(Call);
  1158. // For now, assume that any C++ call can free memory.
  1159. // TODO: If we want to be more optimistic here, we'll need to make sure that
  1160. // regions escape to C++ containers. They seem to do that even now, but for
  1161. // mysterious reasons.
  1162. if (!(isa<FunctionCall>(Call) || isa<ObjCMethodCall>(Call)))
  1163. return false;
  1164. // Check Objective-C messages by selector name.
  1165. if (const ObjCMethodCall *Msg = dyn_cast<ObjCMethodCall>(Call)) {
  1166. // If it's not a framework call, or if it takes a callback, assume it
  1167. // can free memory.
  1168. if (!Call->isInSystemHeader() || Call->hasNonZeroCallbackArg())
  1169. return false;
  1170. Selector S = Msg->getSelector();
  1171. // Whitelist the ObjC methods which do free memory.
  1172. // - Anything containing 'freeWhenDone' param set to 1.
  1173. // Ex: dataWithBytesNoCopy:length:freeWhenDone.
  1174. for (unsigned i = 1; i < S.getNumArgs(); ++i) {
  1175. if (S.getNameForSlot(i).equals("freeWhenDone")) {
  1176. if (Call->getArgSVal(i).isConstant(1))
  1177. return false;
  1178. else
  1179. return true;
  1180. }
  1181. }
  1182. // If the first selector ends with NoCopy, assume that the ownership is
  1183. // transferred as well.
  1184. // Ex: [NSData dataWithBytesNoCopy:bytes length:10];
  1185. StringRef FirstSlot = S.getNameForSlot(0);
  1186. if (FirstSlot.endswith("NoCopy"))
  1187. return false;
  1188. // If the first selector starts with addPointer, insertPointer,
  1189. // or replacePointer, assume we are dealing with NSPointerArray or similar.
  1190. // This is similar to C++ containers (vector); we still might want to check
  1191. // that the pointers get freed by following the container itself.
  1192. if (FirstSlot.startswith("addPointer") ||
  1193. FirstSlot.startswith("insertPointer") ||
  1194. FirstSlot.startswith("replacePointer")) {
  1195. return false;
  1196. }
  1197. // Otherwise, assume that the method does not free memory.
  1198. // Most framework methods do not free memory.
  1199. return true;
  1200. }
  1201. // At this point the only thing left to handle is straight function calls.
  1202. const FunctionDecl *FD = cast<FunctionCall>(Call)->getDecl();
  1203. if (!FD)
  1204. return false;
  1205. ASTContext &ASTC = State->getStateManager().getContext();
  1206. // If it's one of the allocation functions we can reason about, we model
  1207. // its behavior explicitly.
  1208. if (isMemFunction(FD, ASTC))
  1209. return true;
  1210. // If it's not a system call, assume it frees memory.
  1211. if (!Call->isInSystemHeader())
  1212. return false;
  1213. // White list the system functions whose arguments escape.
  1214. const IdentifierInfo *II = FD->getIdentifier();
  1215. if (!II)
  1216. return false;
  1217. StringRef FName = II->getName();
  1218. // White list the 'XXXNoCopy' CoreFoundation functions.
  1219. // We specifically check these before
  1220. if (FName.endswith("NoCopy")) {
  1221. // Look for the deallocator argument. We know that the memory ownership
  1222. // is not transferred only if the deallocator argument is
  1223. // 'kCFAllocatorNull'.
  1224. for (unsigned i = 1; i < Call->getNumArgs(); ++i) {
  1225. const Expr *ArgE = Call->getArgExpr(i)->IgnoreParenCasts();
  1226. if (const DeclRefExpr *DE = dyn_cast<DeclRefExpr>(ArgE)) {
  1227. StringRef DeallocatorName = DE->getFoundDecl()->getName();
  1228. if (DeallocatorName == "kCFAllocatorNull")
  1229. return true;
  1230. }
  1231. }
  1232. return false;
  1233. }
  1234. // Associating streams with malloced buffers. The pointer can escape if
  1235. // 'closefn' is specified (and if that function does free memory),
  1236. // but it will not if closefn is not specified.
  1237. // Currently, we do not inspect the 'closefn' function (PR12101).
  1238. if (FName == "funopen")
  1239. if (Call->getNumArgs() >= 4 && Call->getArgSVal(4).isConstant(0))
  1240. return true;
  1241. // Do not warn on pointers passed to 'setbuf' when used with std streams,
  1242. // these leaks might be intentional when setting the buffer for stdio.
  1243. // http://stackoverflow.com/questions/2671151/who-frees-setvbuf-buffer
  1244. if (FName == "setbuf" || FName =="setbuffer" ||
  1245. FName == "setlinebuf" || FName == "setvbuf") {
  1246. if (Call->getNumArgs() >= 1) {
  1247. const Expr *ArgE = Call->getArgExpr(0)->IgnoreParenCasts();
  1248. if (const DeclRefExpr *ArgDRE = dyn_cast<DeclRefExpr>(ArgE))
  1249. if (const VarDecl *D = dyn_cast<VarDecl>(ArgDRE->getDecl()))
  1250. if (D->getCanonicalDecl()->getName().find("std") != StringRef::npos)
  1251. return false;
  1252. }
  1253. }
  1254. // A bunch of other functions which either take ownership of a pointer or
  1255. // wrap the result up in a struct or object, meaning it can be freed later.
  1256. // (See RetainCountChecker.) Not all the parameters here are invalidated,
  1257. // but the Malloc checker cannot differentiate between them. The right way
  1258. // of doing this would be to implement a pointer escapes callback.
  1259. if (FName == "CGBitmapContextCreate" ||
  1260. FName == "CGBitmapContextCreateWithData" ||
  1261. FName == "CVPixelBufferCreateWithBytes" ||
  1262. FName == "CVPixelBufferCreateWithPlanarBytes" ||
  1263. FName == "OSAtomicEnqueue") {
  1264. return false;
  1265. }
  1266. // Handle cases where we know a buffer's /address/ can escape.
  1267. // Note that the above checks handle some special cases where we know that
  1268. // even though the address escapes, it's still our responsibility to free the
  1269. // buffer.
  1270. if (Call->argumentsMayEscape())
  1271. return false;
  1272. // Otherwise, assume that the function does not free memory.
  1273. // Most system calls do not free the memory.
  1274. return true;
  1275. }
  1276. ProgramStateRef MallocChecker::checkPointerEscape(ProgramStateRef State,
  1277. const InvalidatedSymbols &Escaped,
  1278. const CallEvent *Call,
  1279. PointerEscapeKind Kind) const {
  1280. // If we know that the call does not free memory, keep tracking the top
  1281. // level arguments.
  1282. if ((Kind == PSK_DirectEscapeOnCall ||
  1283. Kind == PSK_IndirectEscapeOnCall) &&
  1284. doesNotFreeMemory(Call, State)) {
  1285. return State;
  1286. }
  1287. for (InvalidatedSymbols::const_iterator I = Escaped.begin(),
  1288. E = Escaped.end();
  1289. I != E; ++I) {
  1290. SymbolRef sym = *I;
  1291. if (const RefState *RS = State->get<RegionState>(sym)) {
  1292. if (RS->isAllocated())
  1293. State = State->remove<RegionState>(sym);
  1294. }
  1295. }
  1296. return State;
  1297. }
  1298. static SymbolRef findFailedReallocSymbol(ProgramStateRef currState,
  1299. ProgramStateRef prevState) {
  1300. ReallocPairsTy currMap = currState->get<ReallocPairs>();
  1301. ReallocPairsTy prevMap = prevState->get<ReallocPairs>();
  1302. for (ReallocPairsTy::iterator I = prevMap.begin(), E = prevMap.end();
  1303. I != E; ++I) {
  1304. SymbolRef sym = I.getKey();
  1305. if (!currMap.lookup(sym))
  1306. return sym;
  1307. }
  1308. return NULL;
  1309. }
  1310. PathDiagnosticPiece *
  1311. MallocChecker::MallocBugVisitor::VisitNode(const ExplodedNode *N,
  1312. const ExplodedNode *PrevN,
  1313. BugReporterContext &BRC,
  1314. BugReport &BR) {
  1315. ProgramStateRef state = N->getState();
  1316. ProgramStateRef statePrev = PrevN->getState();
  1317. const RefState *RS = state->get<RegionState>(Sym);
  1318. const RefState *RSPrev = statePrev->get<RegionState>(Sym);
  1319. if (!RS)
  1320. return 0;
  1321. const Stmt *S = 0;
  1322. const char *Msg = 0;
  1323. StackHintGeneratorForSymbol *StackHint = 0;
  1324. // Retrieve the associated statement.
  1325. ProgramPoint ProgLoc = N->getLocation();
  1326. if (StmtPoint *SP = dyn_cast<StmtPoint>(&ProgLoc)) {
  1327. S = SP->getStmt();
  1328. } else if (CallExitEnd *Exit = dyn_cast<CallExitEnd>(&ProgLoc)) {
  1329. S = Exit->getCalleeContext()->getCallSite();
  1330. } else if (BlockEdge *Edge = dyn_cast<BlockEdge>(&ProgLoc)) {
  1331. // If an assumption was made on a branch, it should be caught
  1332. // here by looking at the state transition.
  1333. S = Edge->getSrc()->getTerminator();
  1334. }
  1335. if (!S)
  1336. return 0;
  1337. // FIXME: We will eventually need to handle non-statement-based events
  1338. // (__attribute__((cleanup))).
  1339. // Find out if this is an interesting point and what is the kind.
  1340. if (Mode == Normal) {
  1341. if (isAllocated(RS, RSPrev, S)) {
  1342. Msg = "Memory is allocated";
  1343. StackHint = new StackHintGeneratorForSymbol(Sym,
  1344. "Returned allocated memory");
  1345. } else if (isReleased(RS, RSPrev, S)) {
  1346. Msg = "Memory is released";
  1347. StackHint = new StackHintGeneratorForSymbol(Sym,
  1348. "Returned released memory");
  1349. } else if (isRelinquished(RS, RSPrev, S)) {
  1350. Msg = "Memory ownership is transfered";
  1351. StackHint = new StackHintGeneratorForSymbol(Sym, "");
  1352. } else if (isReallocFailedCheck(RS, RSPrev, S)) {
  1353. Mode = ReallocationFailed;
  1354. Msg = "Reallocation failed";
  1355. StackHint = new StackHintGeneratorForReallocationFailed(Sym,
  1356. "Reallocation failed");
  1357. if (SymbolRef sym = findFailedReallocSymbol(state, statePrev)) {
  1358. // Is it possible to fail two reallocs WITHOUT testing in between?
  1359. assert((!FailedReallocSymbol || FailedReallocSymbol == sym) &&
  1360. "We only support one failed realloc at a time.");
  1361. BR.markInteresting(sym);
  1362. FailedReallocSymbol = sym;
  1363. }
  1364. }
  1365. // We are in a special mode if a reallocation failed later in the path.
  1366. } else if (Mode == ReallocationFailed) {
  1367. assert(FailedReallocSymbol && "No symbol to look for.");
  1368. // Is this is the first appearance of the reallocated symbol?
  1369. if (!statePrev->get<RegionState>(FailedReallocSymbol)) {
  1370. // We're at the reallocation point.
  1371. Msg = "Attempt to reallocate memory";
  1372. StackHint = new StackHintGeneratorForSymbol(Sym,
  1373. "Returned reallocated memory");
  1374. FailedReallocSymbol = NULL;
  1375. Mode = Normal;
  1376. }
  1377. }
  1378. if (!Msg)
  1379. return 0;
  1380. assert(StackHint);
  1381. // Generate the extra diagnostic.
  1382. PathDiagnosticLocation Pos(S, BRC.getSourceManager(),
  1383. N->getLocationContext());
  1384. return new PathDiagnosticEventPiece(Pos, Msg, true, StackHint);
  1385. }
  1386. void MallocChecker::printState(raw_ostream &Out, ProgramStateRef State,
  1387. const char *NL, const char *Sep) const {
  1388. RegionStateTy RS = State->get<RegionState>();
  1389. if (!RS.isEmpty()) {
  1390. Out << Sep << "MallocChecker:" << NL;
  1391. for (RegionStateTy::iterator I = RS.begin(), E = RS.end(); I != E; ++I) {
  1392. I.getKey()->dumpToStream(Out);
  1393. Out << " : ";
  1394. I.getData().dump(Out);
  1395. Out << NL;
  1396. }
  1397. }
  1398. }
  1399. #define REGISTER_CHECKER(name) \
  1400. void ento::register##name(CheckerManager &mgr) {\
  1401. registerCStringCheckerBasic(mgr); \
  1402. mgr.registerChecker<MallocChecker>()->Filter.C##name = true;\
  1403. }
  1404. REGISTER_CHECKER(MallocPessimistic)
  1405. REGISTER_CHECKER(MallocOptimistic)