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