MallocChecker.cpp 131 KB

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