MallocChecker.cpp 133 KB

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