MallocChecker.cpp 127 KB

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