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