MallocChecker.cpp 127 KB

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