MallocChecker.cpp 114 KB

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