MallocChecker.cpp 114 KB

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