MallocChecker.cpp 105 KB

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