MallocChecker.cpp 116 KB

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