MallocChecker.cpp 114 KB

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