MallocChecker.cpp revision a3ae937ab7b7026953b6e93e0159cf1dd918e2a1
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/Basic/SourceManager.h" 19#include "clang/StaticAnalyzer/Core/BugReporter/BugType.h" 20#include "clang/StaticAnalyzer/Core/Checker.h" 21#include "clang/StaticAnalyzer/Core/CheckerManager.h" 22#include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h" 23#include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h" 24#include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h" 25#include "clang/StaticAnalyzer/Core/PathSensitive/ProgramStateTrait.h" 26#include "clang/StaticAnalyzer/Core/PathSensitive/SymbolManager.h" 27#include "llvm/ADT/ImmutableMap.h" 28#include "llvm/ADT/STLExtras.h" 29#include "llvm/ADT/SmallString.h" 30#include "llvm/ADT/StringExtras.h" 31#include <climits> 32 33using namespace clang; 34using namespace ento; 35 36namespace { 37 38// Used to check correspondence between allocators and deallocators. 39enum AllocationFamily { 40 AF_None, 41 AF_Malloc, 42 AF_CXXNew, 43 AF_CXXNewArray 44}; 45 46class RefState { 47 enum Kind { // Reference to allocated memory. 48 Allocated, 49 // Reference to released/freed memory. 50 Released, 51 // The responsibility for freeing resources has transfered from 52 // this reference. A relinquished symbol should not be freed. 53 Relinquished }; 54 55 const Stmt *S; 56 unsigned K : 2; // Kind enum, but stored as a bitfield. 57 unsigned Family : 30; // Rest of 32-bit word, currently just an allocation 58 // family. 59 60 RefState(Kind k, const Stmt *s, unsigned family) 61 : S(s), K(k), Family(family) {} 62public: 63 bool isAllocated() const { return K == Allocated; } 64 bool isReleased() const { return K == Released; } 65 bool isRelinquished() const { return K == Relinquished; } 66 AllocationFamily getAllocationFamily() const { 67 return (AllocationFamily)Family; 68 } 69 const Stmt *getStmt() const { return S; } 70 71 bool operator==(const RefState &X) const { 72 return K == X.K && S == X.S && Family == X.Family; 73 } 74 75 static RefState getAllocated(unsigned family, const Stmt *s) { 76 return RefState(Allocated, s, family); 77 } 78 static RefState getReleased(unsigned family, const Stmt *s) { 79 return RefState(Released, s, family); 80 } 81 static RefState getRelinquished(unsigned family, const Stmt *s) { 82 return RefState(Relinquished, s, family); 83 } 84 85 void Profile(llvm::FoldingSetNodeID &ID) const { 86 ID.AddInteger(K); 87 ID.AddPointer(S); 88 ID.AddInteger(Family); 89 } 90 91 void dump(raw_ostream &OS) const { 92 static const char *Table[] = { 93 "Allocated", 94 "Released", 95 "Relinquished" 96 }; 97 OS << Table[(unsigned) K]; 98 } 99 100 LLVM_ATTRIBUTE_USED void dump() const { 101 dump(llvm::errs()); 102 } 103}; 104 105enum ReallocPairKind { 106 RPToBeFreedAfterFailure, 107 // The symbol has been freed when reallocation failed. 108 RPIsFreeOnFailure, 109 // The symbol does not need to be freed after reallocation fails. 110 RPDoNotTrackAfterFailure 111}; 112 113/// \class ReallocPair 114/// \brief Stores information about the symbol being reallocated by a call to 115/// 'realloc' to allow modeling failed reallocation later in the path. 116struct ReallocPair { 117 // \brief The symbol which realloc reallocated. 118 SymbolRef ReallocatedSym; 119 ReallocPairKind Kind; 120 121 ReallocPair(SymbolRef S, ReallocPairKind K) : 122 ReallocatedSym(S), Kind(K) {} 123 void Profile(llvm::FoldingSetNodeID &ID) const { 124 ID.AddInteger(Kind); 125 ID.AddPointer(ReallocatedSym); 126 } 127 bool operator==(const ReallocPair &X) const { 128 return ReallocatedSym == X.ReallocatedSym && 129 Kind == X.Kind; 130 } 131}; 132 133typedef std::pair<const ExplodedNode*, const MemRegion*> LeakInfo; 134 135class MallocChecker : public Checker<check::DeadSymbols, 136 check::PointerEscape, 137 check::ConstPointerEscape, 138 check::PreStmt<ReturnStmt>, 139 check::PreStmt<CallExpr>, 140 check::PostStmt<CallExpr>, 141 check::PostStmt<CXXNewExpr>, 142 check::PreStmt<CXXDeleteExpr>, 143 check::PostStmt<BlockExpr>, 144 check::PostObjCMessage, 145 check::Location, 146 eval::Assume> 147{ 148 mutable OwningPtr<BugType> BT_DoubleFree; 149 mutable OwningPtr<BugType> BT_Leak; 150 mutable OwningPtr<BugType> BT_UseFree; 151 mutable OwningPtr<BugType> BT_BadFree; 152 mutable OwningPtr<BugType> BT_MismatchedDealloc; 153 mutable OwningPtr<BugType> BT_OffsetFree; 154 mutable IdentifierInfo *II_malloc, *II_free, *II_realloc, *II_calloc, 155 *II_valloc, *II_reallocf, *II_strndup, *II_strdup; 156 157public: 158 MallocChecker() : II_malloc(0), II_free(0), II_realloc(0), II_calloc(0), 159 II_valloc(0), II_reallocf(0), II_strndup(0), II_strdup(0) {} 160 161 /// In pessimistic mode, the checker assumes that it does not know which 162 /// functions might free the memory. 163 struct ChecksFilter { 164 DefaultBool CMallocPessimistic; 165 DefaultBool CMallocOptimistic; 166 DefaultBool CNewDeleteChecker; 167 DefaultBool CMismatchedDeallocatorChecker; 168 }; 169 170 ChecksFilter Filter; 171 172 void checkPreStmt(const CallExpr *S, CheckerContext &C) const; 173 void checkPostStmt(const CallExpr *CE, CheckerContext &C) const; 174 void checkPostStmt(const CXXNewExpr *NE, CheckerContext &C) const; 175 void checkPreStmt(const CXXDeleteExpr *DE, CheckerContext &C) const; 176 void checkPostObjCMessage(const ObjCMethodCall &Call, CheckerContext &C) const; 177 void checkPostStmt(const BlockExpr *BE, CheckerContext &C) const; 178 void checkDeadSymbols(SymbolReaper &SymReaper, CheckerContext &C) const; 179 void checkPreStmt(const ReturnStmt *S, CheckerContext &C) const; 180 ProgramStateRef evalAssume(ProgramStateRef state, SVal Cond, 181 bool Assumption) const; 182 void checkLocation(SVal l, bool isLoad, const Stmt *S, 183 CheckerContext &C) const; 184 185 ProgramStateRef checkPointerEscape(ProgramStateRef State, 186 const InvalidatedSymbols &Escaped, 187 const CallEvent *Call, 188 PointerEscapeKind Kind) const; 189 ProgramStateRef checkConstPointerEscape(ProgramStateRef State, 190 const InvalidatedSymbols &Escaped, 191 const CallEvent *Call, 192 PointerEscapeKind Kind) const; 193 194 void printState(raw_ostream &Out, ProgramStateRef State, 195 const char *NL, const char *Sep) const; 196 197private: 198 void initIdentifierInfo(ASTContext &C) const; 199 200 /// \brief Determine family of a deallocation expression. 201 AllocationFamily getAllocationFamily(CheckerContext &C, const Stmt *S) const; 202 203 /// \brief Print names of allocators and deallocators. 204 /// 205 /// \returns true on success. 206 bool printAllocDeallocName(raw_ostream &os, CheckerContext &C, 207 const Expr *E) const; 208 209 /// \brief Print expected name of an allocator based on the deallocator's 210 /// family derived from the DeallocExpr. 211 void printExpectedAllocName(raw_ostream &os, CheckerContext &C, 212 const Expr *DeallocExpr) const; 213 /// \brief Print expected name of a deallocator based on the allocator's 214 /// family. 215 void printExpectedDeallocName(raw_ostream &os, AllocationFamily Family) const; 216 217 ///@{ 218 /// Check if this is one of the functions which can allocate/reallocate memory 219 /// pointed to by one of its arguments. 220 bool isMemFunction(const FunctionDecl *FD, ASTContext &C) const; 221 bool isFreeFunction(const FunctionDecl *FD, ASTContext &C) const; 222 bool isAllocationFunction(const FunctionDecl *FD, ASTContext &C) const; 223 bool isStandardNewDelete(const FunctionDecl *FD, ASTContext &C) const; 224 ///@} 225 static ProgramStateRef MallocMemReturnsAttr(CheckerContext &C, 226 const CallExpr *CE, 227 const OwnershipAttr* Att); 228 static ProgramStateRef MallocMemAux(CheckerContext &C, const CallExpr *CE, 229 const Expr *SizeEx, SVal Init, 230 ProgramStateRef State, 231 AllocationFamily Family = AF_Malloc) { 232 return MallocMemAux(C, CE, 233 State->getSVal(SizeEx, C.getLocationContext()), 234 Init, State, Family); 235 } 236 237 static ProgramStateRef MallocMemAux(CheckerContext &C, const CallExpr *CE, 238 SVal SizeEx, SVal Init, 239 ProgramStateRef State, 240 AllocationFamily Family = AF_Malloc); 241 242 /// Update the RefState to reflect the new memory allocation. 243 static ProgramStateRef 244 MallocUpdateRefState(CheckerContext &C, const Expr *E, ProgramStateRef State, 245 AllocationFamily Family = AF_Malloc); 246 247 ProgramStateRef FreeMemAttr(CheckerContext &C, const CallExpr *CE, 248 const OwnershipAttr* Att) const; 249 ProgramStateRef FreeMemAux(CheckerContext &C, const CallExpr *CE, 250 ProgramStateRef state, unsigned Num, 251 bool Hold, 252 bool &ReleasedAllocated, 253 bool ReturnsNullOnFailure = false) const; 254 ProgramStateRef FreeMemAux(CheckerContext &C, const Expr *Arg, 255 const Expr *ParentExpr, 256 ProgramStateRef State, 257 bool Hold, 258 bool &ReleasedAllocated, 259 bool ReturnsNullOnFailure = false) const; 260 261 ProgramStateRef ReallocMem(CheckerContext &C, const CallExpr *CE, 262 bool FreesMemOnFailure) const; 263 static ProgramStateRef CallocMem(CheckerContext &C, const CallExpr *CE); 264 265 ///\brief Check if the memory associated with this symbol was released. 266 bool isReleased(SymbolRef Sym, CheckerContext &C) const; 267 268 bool checkUseAfterFree(SymbolRef Sym, CheckerContext &C, const Stmt *S) const; 269 270 /// Check if the function is known not to free memory, or if it is 271 /// "interesting" and should be modeled explicitly. 272 /// 273 /// We assume that pointers do not escape through calls to system functions 274 /// not handled by this checker. 275 bool doesNotFreeMemOrInteresting(const CallEvent *Call, 276 ProgramStateRef State) const; 277 278 // Implementation of the checkPointerEscape callabcks. 279 ProgramStateRef checkPointerEscapeAux(ProgramStateRef State, 280 const InvalidatedSymbols &Escaped, 281 const CallEvent *Call, 282 PointerEscapeKind Kind, 283 bool(*CheckRefState)(const RefState*)) const; 284 285 // Used to suppress warnings if they are not related to the tracked family 286 // (derived from AllocDeallocStmt). 287 bool isTrackedFamily(AllocationFamily Family) const; 288 bool isTrackedFamily(CheckerContext &C, const Stmt *AllocDeallocStmt) const; 289 bool isTrackedFamily(CheckerContext &C, SymbolRef Sym) const; 290 291 static bool SummarizeValue(raw_ostream &os, SVal V); 292 static bool SummarizeRegion(raw_ostream &os, const MemRegion *MR); 293 void ReportBadFree(CheckerContext &C, SVal ArgVal, SourceRange Range, 294 const Expr *DeallocExpr) const; 295 void ReportMismatchedDealloc(CheckerContext &C, SourceRange Range, 296 const Expr *DeallocExpr, const RefState *RS, 297 SymbolRef Sym) const; 298 void ReportOffsetFree(CheckerContext &C, SVal ArgVal, SourceRange Range, 299 const Expr *DeallocExpr, 300 const Expr *AllocExpr = 0) const; 301 void ReportUseAfterFree(CheckerContext &C, SourceRange Range, 302 SymbolRef Sym) const; 303 void ReportDoubleFree(CheckerContext &C, SourceRange Range, bool Released, 304 SymbolRef Sym, SymbolRef PrevSym) const; 305 306 /// Find the location of the allocation for Sym on the path leading to the 307 /// exploded node N. 308 LeakInfo getAllocationSite(const ExplodedNode *N, SymbolRef Sym, 309 CheckerContext &C) const; 310 311 void reportLeak(SymbolRef Sym, ExplodedNode *N, CheckerContext &C) const; 312 313 /// The bug visitor which allows us to print extra diagnostics along the 314 /// BugReport path. For example, showing the allocation site of the leaked 315 /// region. 316 class MallocBugVisitor : public BugReporterVisitorImpl<MallocBugVisitor> { 317 protected: 318 enum NotificationMode { 319 Normal, 320 ReallocationFailed 321 }; 322 323 // The allocated region symbol tracked by the main analysis. 324 SymbolRef Sym; 325 326 // The mode we are in, i.e. what kind of diagnostics will be emitted. 327 NotificationMode Mode; 328 329 // A symbol from when the primary region should have been reallocated. 330 SymbolRef FailedReallocSymbol; 331 332 bool IsLeak; 333 334 public: 335 MallocBugVisitor(SymbolRef S, bool isLeak = false) 336 : Sym(S), Mode(Normal), FailedReallocSymbol(0), IsLeak(isLeak) {} 337 338 virtual ~MallocBugVisitor() {} 339 340 void Profile(llvm::FoldingSetNodeID &ID) const { 341 static int X = 0; 342 ID.AddPointer(&X); 343 ID.AddPointer(Sym); 344 } 345 346 inline bool isAllocated(const RefState *S, const RefState *SPrev, 347 const Stmt *Stmt) { 348 // Did not track -> allocated. Other state (released) -> allocated. 349 return (Stmt && (isa<CallExpr>(Stmt) || isa<CXXNewExpr>(Stmt)) && 350 (S && S->isAllocated()) && (!SPrev || !SPrev->isAllocated())); 351 } 352 353 inline bool isReleased(const RefState *S, const RefState *SPrev, 354 const Stmt *Stmt) { 355 // Did not track -> released. Other state (allocated) -> released. 356 return (Stmt && (isa<CallExpr>(Stmt) || isa<CXXDeleteExpr>(Stmt)) && 357 (S && S->isReleased()) && (!SPrev || !SPrev->isReleased())); 358 } 359 360 inline bool isRelinquished(const RefState *S, const RefState *SPrev, 361 const Stmt *Stmt) { 362 // Did not track -> relinquished. Other state (allocated) -> relinquished. 363 return (Stmt && (isa<CallExpr>(Stmt) || isa<ObjCMessageExpr>(Stmt) || 364 isa<ObjCPropertyRefExpr>(Stmt)) && 365 (S && S->isRelinquished()) && 366 (!SPrev || !SPrev->isRelinquished())); 367 } 368 369 inline bool isReallocFailedCheck(const RefState *S, const RefState *SPrev, 370 const Stmt *Stmt) { 371 // If the expression is not a call, and the state change is 372 // released -> allocated, it must be the realloc return value 373 // check. If we have to handle more cases here, it might be cleaner just 374 // to track this extra bit in the state itself. 375 return ((!Stmt || !isa<CallExpr>(Stmt)) && 376 (S && S->isAllocated()) && (SPrev && !SPrev->isAllocated())); 377 } 378 379 PathDiagnosticPiece *VisitNode(const ExplodedNode *N, 380 const ExplodedNode *PrevN, 381 BugReporterContext &BRC, 382 BugReport &BR); 383 384 PathDiagnosticPiece* getEndPath(BugReporterContext &BRC, 385 const ExplodedNode *EndPathNode, 386 BugReport &BR) { 387 if (!IsLeak) 388 return 0; 389 390 PathDiagnosticLocation L = 391 PathDiagnosticLocation::createEndOfPath(EndPathNode, 392 BRC.getSourceManager()); 393 // Do not add the statement itself as a range in case of leak. 394 return new PathDiagnosticEventPiece(L, BR.getDescription(), false); 395 } 396 397 private: 398 class StackHintGeneratorForReallocationFailed 399 : public StackHintGeneratorForSymbol { 400 public: 401 StackHintGeneratorForReallocationFailed(SymbolRef S, StringRef M) 402 : StackHintGeneratorForSymbol(S, M) {} 403 404 virtual std::string getMessageForArg(const Expr *ArgE, unsigned ArgIndex) { 405 // Printed parameters start at 1, not 0. 406 ++ArgIndex; 407 408 SmallString<200> buf; 409 llvm::raw_svector_ostream os(buf); 410 411 os << "Reallocation of " << ArgIndex << llvm::getOrdinalSuffix(ArgIndex) 412 << " parameter failed"; 413 414 return os.str(); 415 } 416 417 virtual std::string getMessageForReturn(const CallExpr *CallExpr) { 418 return "Reallocation of returned value failed"; 419 } 420 }; 421 }; 422}; 423} // end anonymous namespace 424 425REGISTER_MAP_WITH_PROGRAMSTATE(RegionState, SymbolRef, RefState) 426REGISTER_MAP_WITH_PROGRAMSTATE(ReallocPairs, SymbolRef, ReallocPair) 427 428// A map from the freed symbol to the symbol representing the return value of 429// the free function. 430REGISTER_MAP_WITH_PROGRAMSTATE(FreeReturnValue, SymbolRef, SymbolRef) 431 432namespace { 433class StopTrackingCallback : public SymbolVisitor { 434 ProgramStateRef state; 435public: 436 StopTrackingCallback(ProgramStateRef st) : state(st) {} 437 ProgramStateRef getState() const { return state; } 438 439 bool VisitSymbol(SymbolRef sym) { 440 state = state->remove<RegionState>(sym); 441 return true; 442 } 443}; 444} // end anonymous namespace 445 446void MallocChecker::initIdentifierInfo(ASTContext &Ctx) const { 447 if (II_malloc) 448 return; 449 II_malloc = &Ctx.Idents.get("malloc"); 450 II_free = &Ctx.Idents.get("free"); 451 II_realloc = &Ctx.Idents.get("realloc"); 452 II_reallocf = &Ctx.Idents.get("reallocf"); 453 II_calloc = &Ctx.Idents.get("calloc"); 454 II_valloc = &Ctx.Idents.get("valloc"); 455 II_strdup = &Ctx.Idents.get("strdup"); 456 II_strndup = &Ctx.Idents.get("strndup"); 457} 458 459bool MallocChecker::isMemFunction(const FunctionDecl *FD, ASTContext &C) const { 460 if (isFreeFunction(FD, C)) 461 return true; 462 463 if (isAllocationFunction(FD, C)) 464 return true; 465 466 if (isStandardNewDelete(FD, C)) 467 return true; 468 469 return false; 470} 471 472bool MallocChecker::isAllocationFunction(const FunctionDecl *FD, 473 ASTContext &C) const { 474 if (!FD) 475 return false; 476 477 if (FD->getKind() == Decl::Function) { 478 IdentifierInfo *FunI = FD->getIdentifier(); 479 initIdentifierInfo(C); 480 481 if (FunI == II_malloc || FunI == II_realloc || 482 FunI == II_reallocf || FunI == II_calloc || FunI == II_valloc || 483 FunI == II_strdup || FunI == II_strndup) 484 return true; 485 } 486 487 if (Filter.CMallocOptimistic && FD->hasAttrs()) 488 for (specific_attr_iterator<OwnershipAttr> 489 i = FD->specific_attr_begin<OwnershipAttr>(), 490 e = FD->specific_attr_end<OwnershipAttr>(); 491 i != e; ++i) 492 if ((*i)->getOwnKind() == OwnershipAttr::Returns) 493 return true; 494 return false; 495} 496 497bool MallocChecker::isFreeFunction(const FunctionDecl *FD, ASTContext &C) const { 498 if (!FD) 499 return false; 500 501 if (FD->getKind() == Decl::Function) { 502 IdentifierInfo *FunI = FD->getIdentifier(); 503 initIdentifierInfo(C); 504 505 if (FunI == II_free || FunI == II_realloc || FunI == II_reallocf) 506 return true; 507 } 508 509 if (Filter.CMallocOptimistic && FD->hasAttrs()) 510 for (specific_attr_iterator<OwnershipAttr> 511 i = FD->specific_attr_begin<OwnershipAttr>(), 512 e = FD->specific_attr_end<OwnershipAttr>(); 513 i != e; ++i) 514 if ((*i)->getOwnKind() == OwnershipAttr::Takes || 515 (*i)->getOwnKind() == OwnershipAttr::Holds) 516 return true; 517 return false; 518} 519 520// Tells if the callee is one of the following: 521// 1) A global non-placement new/delete operator function. 522// 2) A global placement operator function with the single placement argument 523// of type std::nothrow_t. 524bool MallocChecker::isStandardNewDelete(const FunctionDecl *FD, 525 ASTContext &C) const { 526 if (!FD) 527 return false; 528 529 OverloadedOperatorKind Kind = FD->getOverloadedOperator(); 530 if (Kind != OO_New && Kind != OO_Array_New && 531 Kind != OO_Delete && Kind != OO_Array_Delete) 532 return false; 533 534 // Skip all operator new/delete methods. 535 if (isa<CXXMethodDecl>(FD)) 536 return false; 537 538 // Return true if tested operator is a standard placement nothrow operator. 539 if (FD->getNumParams() == 2) { 540 QualType T = FD->getParamDecl(1)->getType(); 541 if (const IdentifierInfo *II = T.getBaseTypeIdentifier()) 542 return II->getName().equals("nothrow_t"); 543 } 544 545 // Skip placement operators. 546 if (FD->getNumParams() != 1 || FD->isVariadic()) 547 return false; 548 549 // One of the standard new/new[]/delete/delete[] non-placement operators. 550 return true; 551} 552 553void MallocChecker::checkPostStmt(const CallExpr *CE, CheckerContext &C) const { 554 if (C.wasInlined) 555 return; 556 557 const FunctionDecl *FD = C.getCalleeDecl(CE); 558 if (!FD) 559 return; 560 561 ProgramStateRef State = C.getState(); 562 bool ReleasedAllocatedMemory = false; 563 564 if (FD->getKind() == Decl::Function) { 565 initIdentifierInfo(C.getASTContext()); 566 IdentifierInfo *FunI = FD->getIdentifier(); 567 568 if (FunI == II_malloc || FunI == II_valloc) { 569 if (CE->getNumArgs() < 1) 570 return; 571 State = MallocMemAux(C, CE, CE->getArg(0), UndefinedVal(), State); 572 } else if (FunI == II_realloc) { 573 State = ReallocMem(C, CE, false); 574 } else if (FunI == II_reallocf) { 575 State = ReallocMem(C, CE, true); 576 } else if (FunI == II_calloc) { 577 State = CallocMem(C, CE); 578 } else if (FunI == II_free) { 579 State = FreeMemAux(C, CE, State, 0, false, ReleasedAllocatedMemory); 580 } else if (FunI == II_strdup) { 581 State = MallocUpdateRefState(C, CE, State); 582 } else if (FunI == II_strndup) { 583 State = MallocUpdateRefState(C, CE, State); 584 } 585 else if (isStandardNewDelete(FD, C.getASTContext())) { 586 // Process direct calls to operator new/new[]/delete/delete[] functions 587 // as distinct from new/new[]/delete/delete[] expressions that are 588 // processed by the checkPostStmt callbacks for CXXNewExpr and 589 // CXXDeleteExpr. 590 OverloadedOperatorKind K = FD->getOverloadedOperator(); 591 if (K == OO_New) 592 State = MallocMemAux(C, CE, CE->getArg(0), UndefinedVal(), State, 593 AF_CXXNew); 594 else if (K == OO_Array_New) 595 State = MallocMemAux(C, CE, CE->getArg(0), UndefinedVal(), State, 596 AF_CXXNewArray); 597 else if (K == OO_Delete || K == OO_Array_Delete) 598 State = FreeMemAux(C, CE, State, 0, false, ReleasedAllocatedMemory); 599 else 600 llvm_unreachable("not a new/delete operator"); 601 } 602 } 603 604 if (Filter.CMallocOptimistic || Filter.CMismatchedDeallocatorChecker) { 605 // Check all the attributes, if there are any. 606 // There can be multiple of these attributes. 607 if (FD->hasAttrs()) 608 for (specific_attr_iterator<OwnershipAttr> 609 i = FD->specific_attr_begin<OwnershipAttr>(), 610 e = FD->specific_attr_end<OwnershipAttr>(); 611 i != e; ++i) { 612 switch ((*i)->getOwnKind()) { 613 case OwnershipAttr::Returns: 614 State = MallocMemReturnsAttr(C, CE, *i); 615 break; 616 case OwnershipAttr::Takes: 617 case OwnershipAttr::Holds: 618 State = FreeMemAttr(C, CE, *i); 619 break; 620 } 621 } 622 } 623 C.addTransition(State); 624} 625 626void MallocChecker::checkPostStmt(const CXXNewExpr *NE, 627 CheckerContext &C) const { 628 629 if (NE->getNumPlacementArgs()) 630 for (CXXNewExpr::const_arg_iterator I = NE->placement_arg_begin(), 631 E = NE->placement_arg_end(); I != E; ++I) 632 if (SymbolRef Sym = C.getSVal(*I).getAsSymbol()) 633 checkUseAfterFree(Sym, C, *I); 634 635 if (!isStandardNewDelete(NE->getOperatorNew(), C.getASTContext())) 636 return; 637 638 ProgramStateRef State = C.getState(); 639 // The return value from operator new is bound to a specified initialization 640 // value (if any) and we don't want to loose this value. So we call 641 // MallocUpdateRefState() instead of MallocMemAux() which breakes the 642 // existing binding. 643 State = MallocUpdateRefState(C, NE, State, NE->isArray() ? AF_CXXNewArray 644 : AF_CXXNew); 645 C.addTransition(State); 646} 647 648void MallocChecker::checkPreStmt(const CXXDeleteExpr *DE, 649 CheckerContext &C) const { 650 651 if (!Filter.CNewDeleteChecker) 652 if (SymbolRef Sym = C.getSVal(DE->getArgument()).getAsSymbol()) 653 checkUseAfterFree(Sym, C, DE->getArgument()); 654 655 if (!isStandardNewDelete(DE->getOperatorDelete(), C.getASTContext())) 656 return; 657 658 ProgramStateRef State = C.getState(); 659 bool ReleasedAllocated; 660 State = FreeMemAux(C, DE->getArgument(), DE, State, 661 /*Hold*/false, ReleasedAllocated); 662 663 C.addTransition(State); 664} 665 666static bool isKnownDeallocObjCMethodName(const ObjCMethodCall &Call) { 667 // If the first selector piece is one of the names below, assume that the 668 // object takes ownership of the memory, promising to eventually deallocate it 669 // with free(). 670 // Ex: [NSData dataWithBytesNoCopy:bytes length:10]; 671 // (...unless a 'freeWhenDone' parameter is false, but that's checked later.) 672 StringRef FirstSlot = Call.getSelector().getNameForSlot(0); 673 if (FirstSlot == "dataWithBytesNoCopy" || 674 FirstSlot == "initWithBytesNoCopy" || 675 FirstSlot == "initWithCharactersNoCopy") 676 return true; 677 678 return false; 679} 680 681static Optional<bool> getFreeWhenDoneArg(const ObjCMethodCall &Call) { 682 Selector S = Call.getSelector(); 683 684 // FIXME: We should not rely on fully-constrained symbols being folded. 685 for (unsigned i = 1; i < S.getNumArgs(); ++i) 686 if (S.getNameForSlot(i).equals("freeWhenDone")) 687 return !Call.getArgSVal(i).isZeroConstant(); 688 689 return None; 690} 691 692void MallocChecker::checkPostObjCMessage(const ObjCMethodCall &Call, 693 CheckerContext &C) const { 694 if (C.wasInlined) 695 return; 696 697 if (!isKnownDeallocObjCMethodName(Call)) 698 return; 699 700 if (Optional<bool> FreeWhenDone = getFreeWhenDoneArg(Call)) 701 if (!*FreeWhenDone) 702 return; 703 704 bool ReleasedAllocatedMemory; 705 ProgramStateRef State = FreeMemAux(C, Call.getArgExpr(0), 706 Call.getOriginExpr(), C.getState(), 707 /*Hold=*/true, ReleasedAllocatedMemory, 708 /*RetNullOnFailure=*/true); 709 710 C.addTransition(State); 711} 712 713ProgramStateRef MallocChecker::MallocMemReturnsAttr(CheckerContext &C, 714 const CallExpr *CE, 715 const OwnershipAttr* Att) { 716 if (Att->getModule() != "malloc") 717 return 0; 718 719 OwnershipAttr::args_iterator I = Att->args_begin(), E = Att->args_end(); 720 if (I != E) { 721 return MallocMemAux(C, CE, CE->getArg(*I), UndefinedVal(), C.getState()); 722 } 723 return MallocMemAux(C, CE, UnknownVal(), UndefinedVal(), C.getState()); 724} 725 726ProgramStateRef MallocChecker::MallocMemAux(CheckerContext &C, 727 const CallExpr *CE, 728 SVal Size, SVal Init, 729 ProgramStateRef State, 730 AllocationFamily Family) { 731 732 // Bind the return value to the symbolic value from the heap region. 733 // TODO: We could rewrite post visit to eval call; 'malloc' does not have 734 // side effects other than what we model here. 735 unsigned Count = C.blockCount(); 736 SValBuilder &svalBuilder = C.getSValBuilder(); 737 const LocationContext *LCtx = C.getPredecessor()->getLocationContext(); 738 DefinedSVal RetVal = svalBuilder.getConjuredHeapSymbolVal(CE, LCtx, Count) 739 .castAs<DefinedSVal>(); 740 State = State->BindExpr(CE, C.getLocationContext(), RetVal); 741 742 // We expect the malloc functions to return a pointer. 743 if (!RetVal.getAs<Loc>()) 744 return 0; 745 746 // Fill the region with the initialization value. 747 State = State->bindDefault(RetVal, Init); 748 749 // Set the region's extent equal to the Size parameter. 750 const SymbolicRegion *R = 751 dyn_cast_or_null<SymbolicRegion>(RetVal.getAsRegion()); 752 if (!R) 753 return 0; 754 if (Optional<DefinedOrUnknownSVal> DefinedSize = 755 Size.getAs<DefinedOrUnknownSVal>()) { 756 SValBuilder &svalBuilder = C.getSValBuilder(); 757 DefinedOrUnknownSVal Extent = R->getExtent(svalBuilder); 758 DefinedOrUnknownSVal extentMatchesSize = 759 svalBuilder.evalEQ(State, Extent, *DefinedSize); 760 761 State = State->assume(extentMatchesSize, true); 762 assert(State); 763 } 764 765 return MallocUpdateRefState(C, CE, State, Family); 766} 767 768ProgramStateRef MallocChecker::MallocUpdateRefState(CheckerContext &C, 769 const Expr *E, 770 ProgramStateRef State, 771 AllocationFamily Family) { 772 // Get the return value. 773 SVal retVal = State->getSVal(E, C.getLocationContext()); 774 775 // We expect the malloc functions to return a pointer. 776 if (!retVal.getAs<Loc>()) 777 return 0; 778 779 SymbolRef Sym = retVal.getAsLocSymbol(); 780 assert(Sym); 781 782 // Set the symbol's state to Allocated. 783 return State->set<RegionState>(Sym, RefState::getAllocated(Family, E)); 784} 785 786ProgramStateRef MallocChecker::FreeMemAttr(CheckerContext &C, 787 const CallExpr *CE, 788 const OwnershipAttr* Att) const { 789 if (Att->getModule() != "malloc") 790 return 0; 791 792 ProgramStateRef State = C.getState(); 793 bool ReleasedAllocated = false; 794 795 for (OwnershipAttr::args_iterator I = Att->args_begin(), E = Att->args_end(); 796 I != E; ++I) { 797 ProgramStateRef StateI = FreeMemAux(C, CE, State, *I, 798 Att->getOwnKind() == OwnershipAttr::Holds, 799 ReleasedAllocated); 800 if (StateI) 801 State = StateI; 802 } 803 return State; 804} 805 806ProgramStateRef MallocChecker::FreeMemAux(CheckerContext &C, 807 const CallExpr *CE, 808 ProgramStateRef state, 809 unsigned Num, 810 bool Hold, 811 bool &ReleasedAllocated, 812 bool ReturnsNullOnFailure) const { 813 if (CE->getNumArgs() < (Num + 1)) 814 return 0; 815 816 return FreeMemAux(C, CE->getArg(Num), CE, state, Hold, 817 ReleasedAllocated, ReturnsNullOnFailure); 818} 819 820/// Checks if the previous call to free on the given symbol failed - if free 821/// failed, returns true. Also, returns the corresponding return value symbol. 822static bool didPreviousFreeFail(ProgramStateRef State, 823 SymbolRef Sym, SymbolRef &RetStatusSymbol) { 824 const SymbolRef *Ret = State->get<FreeReturnValue>(Sym); 825 if (Ret) { 826 assert(*Ret && "We should not store the null return symbol"); 827 ConstraintManager &CMgr = State->getConstraintManager(); 828 ConditionTruthVal FreeFailed = CMgr.isNull(State, *Ret); 829 RetStatusSymbol = *Ret; 830 return FreeFailed.isConstrainedTrue(); 831 } 832 return false; 833} 834 835AllocationFamily MallocChecker::getAllocationFamily(CheckerContext &C, 836 const Stmt *S) const { 837 if (!S) 838 return AF_None; 839 840 if (const CallExpr *CE = dyn_cast<CallExpr>(S)) { 841 const FunctionDecl *FD = C.getCalleeDecl(CE); 842 843 if (!FD) 844 FD = dyn_cast<FunctionDecl>(CE->getCalleeDecl()); 845 846 ASTContext &Ctx = C.getASTContext(); 847 848 if (isAllocationFunction(FD, Ctx) || isFreeFunction(FD, Ctx)) 849 return AF_Malloc; 850 851 if (isStandardNewDelete(FD, Ctx)) { 852 OverloadedOperatorKind Kind = FD->getOverloadedOperator(); 853 if (Kind == OO_New || Kind == OO_Delete) 854 return AF_CXXNew; 855 else if (Kind == OO_Array_New || Kind == OO_Array_Delete) 856 return AF_CXXNewArray; 857 } 858 859 return AF_None; 860 } 861 862 if (const CXXNewExpr *NE = dyn_cast<CXXNewExpr>(S)) 863 return NE->isArray() ? AF_CXXNewArray : AF_CXXNew; 864 865 if (const CXXDeleteExpr *DE = dyn_cast<CXXDeleteExpr>(S)) 866 return DE->isArrayForm() ? AF_CXXNewArray : AF_CXXNew; 867 868 if (isa<ObjCMessageExpr>(S)) 869 return AF_Malloc; 870 871 return AF_None; 872} 873 874bool MallocChecker::printAllocDeallocName(raw_ostream &os, CheckerContext &C, 875 const Expr *E) const { 876 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) { 877 // FIXME: This doesn't handle indirect calls. 878 const FunctionDecl *FD = CE->getDirectCallee(); 879 if (!FD) 880 return false; 881 882 os << *FD; 883 if (!FD->isOverloadedOperator()) 884 os << "()"; 885 return true; 886 } 887 888 if (const ObjCMessageExpr *Msg = dyn_cast<ObjCMessageExpr>(E)) { 889 if (Msg->isInstanceMessage()) 890 os << "-"; 891 else 892 os << "+"; 893 os << Msg->getSelector().getAsString(); 894 return true; 895 } 896 897 if (const CXXNewExpr *NE = dyn_cast<CXXNewExpr>(E)) { 898 os << "'" 899 << getOperatorSpelling(NE->getOperatorNew()->getOverloadedOperator()) 900 << "'"; 901 return true; 902 } 903 904 if (const CXXDeleteExpr *DE = dyn_cast<CXXDeleteExpr>(E)) { 905 os << "'" 906 << getOperatorSpelling(DE->getOperatorDelete()->getOverloadedOperator()) 907 << "'"; 908 return true; 909 } 910 911 return false; 912} 913 914void MallocChecker::printExpectedAllocName(raw_ostream &os, CheckerContext &C, 915 const Expr *E) const { 916 AllocationFamily Family = getAllocationFamily(C, E); 917 918 switch(Family) { 919 case AF_Malloc: os << "malloc()"; return; 920 case AF_CXXNew: os << "'new'"; return; 921 case AF_CXXNewArray: os << "'new[]'"; return; 922 case AF_None: llvm_unreachable("not a deallocation expression"); 923 } 924} 925 926void MallocChecker::printExpectedDeallocName(raw_ostream &os, 927 AllocationFamily Family) const { 928 switch(Family) { 929 case AF_Malloc: os << "free()"; return; 930 case AF_CXXNew: os << "'delete'"; return; 931 case AF_CXXNewArray: os << "'delete[]'"; return; 932 case AF_None: llvm_unreachable("suspicious AF_None argument"); 933 } 934} 935 936ProgramStateRef MallocChecker::FreeMemAux(CheckerContext &C, 937 const Expr *ArgExpr, 938 const Expr *ParentExpr, 939 ProgramStateRef State, 940 bool Hold, 941 bool &ReleasedAllocated, 942 bool ReturnsNullOnFailure) const { 943 944 SVal ArgVal = State->getSVal(ArgExpr, C.getLocationContext()); 945 if (!ArgVal.getAs<DefinedOrUnknownSVal>()) 946 return 0; 947 DefinedOrUnknownSVal location = ArgVal.castAs<DefinedOrUnknownSVal>(); 948 949 // Check for null dereferences. 950 if (!location.getAs<Loc>()) 951 return 0; 952 953 // The explicit NULL case, no operation is performed. 954 ProgramStateRef notNullState, nullState; 955 llvm::tie(notNullState, nullState) = State->assume(location); 956 if (nullState && !notNullState) 957 return 0; 958 959 // Unknown values could easily be okay 960 // Undefined values are handled elsewhere 961 if (ArgVal.isUnknownOrUndef()) 962 return 0; 963 964 const MemRegion *R = ArgVal.getAsRegion(); 965 966 // Nonlocs can't be freed, of course. 967 // Non-region locations (labels and fixed addresses) also shouldn't be freed. 968 if (!R) { 969 ReportBadFree(C, ArgVal, ArgExpr->getSourceRange(), ParentExpr); 970 return 0; 971 } 972 973 R = R->StripCasts(); 974 975 // Blocks might show up as heap data, but should not be free()d 976 if (isa<BlockDataRegion>(R)) { 977 ReportBadFree(C, ArgVal, ArgExpr->getSourceRange(), ParentExpr); 978 return 0; 979 } 980 981 const MemSpaceRegion *MS = R->getMemorySpace(); 982 983 // Parameters, locals, statics, globals, and memory returned by alloca() 984 // shouldn't be freed. 985 if (!(isa<UnknownSpaceRegion>(MS) || isa<HeapSpaceRegion>(MS))) { 986 // FIXME: at the time this code was written, malloc() regions were 987 // represented by conjured symbols, which are all in UnknownSpaceRegion. 988 // This means that there isn't actually anything from HeapSpaceRegion 989 // that should be freed, even though we allow it here. 990 // Of course, free() can work on memory allocated outside the current 991 // function, so UnknownSpaceRegion is always a possibility. 992 // False negatives are better than false positives. 993 994 ReportBadFree(C, ArgVal, ArgExpr->getSourceRange(), ParentExpr); 995 return 0; 996 } 997 998 const SymbolicRegion *SrBase = dyn_cast<SymbolicRegion>(R->getBaseRegion()); 999 // Various cases could lead to non-symbol values here. 1000 // For now, ignore them. 1001 if (!SrBase) 1002 return 0; 1003 1004 SymbolRef SymBase = SrBase->getSymbol(); 1005 const RefState *RsBase = State->get<RegionState>(SymBase); 1006 SymbolRef PreviousRetStatusSymbol = 0; 1007 1008 if (RsBase) { 1009 1010 bool DeallocMatchesAlloc = 1011 RsBase->getAllocationFamily() == AF_None || 1012 RsBase->getAllocationFamily() == getAllocationFamily(C, ParentExpr); 1013 1014 // Check if an expected deallocation function matches the real one. 1015 if (!DeallocMatchesAlloc && RsBase->isAllocated()) { 1016 ReportMismatchedDealloc(C, ArgExpr->getSourceRange(), ParentExpr, RsBase, 1017 SymBase); 1018 return 0; 1019 } 1020 1021 // Check double free. 1022 if (DeallocMatchesAlloc && 1023 (RsBase->isReleased() || RsBase->isRelinquished()) && 1024 !didPreviousFreeFail(State, SymBase, PreviousRetStatusSymbol)) { 1025 ReportDoubleFree(C, ParentExpr->getSourceRange(), RsBase->isReleased(), 1026 SymBase, PreviousRetStatusSymbol); 1027 return 0; 1028 } 1029 1030 // Check if the memory location being freed is the actual location 1031 // allocated, or an offset. 1032 RegionOffset Offset = R->getAsOffset(); 1033 if (RsBase->isAllocated() && 1034 Offset.isValid() && 1035 !Offset.hasSymbolicOffset() && 1036 Offset.getOffset() != 0) { 1037 const Expr *AllocExpr = cast<Expr>(RsBase->getStmt()); 1038 ReportOffsetFree(C, ArgVal, ArgExpr->getSourceRange(), ParentExpr, 1039 AllocExpr); 1040 return 0; 1041 } 1042 } 1043 1044 ReleasedAllocated = (RsBase != 0); 1045 1046 // Clean out the info on previous call to free return info. 1047 State = State->remove<FreeReturnValue>(SymBase); 1048 1049 // Keep track of the return value. If it is NULL, we will know that free 1050 // failed. 1051 if (ReturnsNullOnFailure) { 1052 SVal RetVal = C.getSVal(ParentExpr); 1053 SymbolRef RetStatusSymbol = RetVal.getAsSymbol(); 1054 if (RetStatusSymbol) { 1055 C.getSymbolManager().addSymbolDependency(SymBase, RetStatusSymbol); 1056 State = State->set<FreeReturnValue>(SymBase, RetStatusSymbol); 1057 } 1058 } 1059 1060 AllocationFamily Family = RsBase ? RsBase->getAllocationFamily() : AF_None; 1061 // Normal free. 1062 if (Hold) 1063 return State->set<RegionState>(SymBase, 1064 RefState::getRelinquished(Family, 1065 ParentExpr)); 1066 1067 return State->set<RegionState>(SymBase, 1068 RefState::getReleased(Family, ParentExpr)); 1069} 1070 1071bool MallocChecker::isTrackedFamily(AllocationFamily Family) const { 1072 switch (Family) { 1073 case AF_Malloc: { 1074 if (!Filter.CMallocOptimistic && !Filter.CMallocPessimistic) 1075 return false; 1076 return true; 1077 } 1078 case AF_CXXNew: 1079 case AF_CXXNewArray: { 1080 if (!Filter.CNewDeleteChecker) 1081 return false; 1082 return true; 1083 } 1084 case AF_None: { 1085 return true; 1086 } 1087 } 1088 llvm_unreachable("unhandled family"); 1089} 1090 1091bool MallocChecker::isTrackedFamily(CheckerContext &C, 1092 const Stmt *AllocDeallocStmt) const { 1093 return isTrackedFamily(getAllocationFamily(C, AllocDeallocStmt)); 1094} 1095 1096bool MallocChecker::isTrackedFamily(CheckerContext &C, SymbolRef Sym) const { 1097 const RefState *RS = C.getState()->get<RegionState>(Sym); 1098 1099 return RS ? isTrackedFamily(RS->getAllocationFamily()) 1100 : isTrackedFamily(AF_None); 1101} 1102 1103bool MallocChecker::SummarizeValue(raw_ostream &os, SVal V) { 1104 if (Optional<nonloc::ConcreteInt> IntVal = V.getAs<nonloc::ConcreteInt>()) 1105 os << "an integer (" << IntVal->getValue() << ")"; 1106 else if (Optional<loc::ConcreteInt> ConstAddr = V.getAs<loc::ConcreteInt>()) 1107 os << "a constant address (" << ConstAddr->getValue() << ")"; 1108 else if (Optional<loc::GotoLabel> Label = V.getAs<loc::GotoLabel>()) 1109 os << "the address of the label '" << Label->getLabel()->getName() << "'"; 1110 else 1111 return false; 1112 1113 return true; 1114} 1115 1116bool MallocChecker::SummarizeRegion(raw_ostream &os, 1117 const MemRegion *MR) { 1118 switch (MR->getKind()) { 1119 case MemRegion::FunctionTextRegionKind: { 1120 const NamedDecl *FD = cast<FunctionTextRegion>(MR)->getDecl(); 1121 if (FD) 1122 os << "the address of the function '" << *FD << '\''; 1123 else 1124 os << "the address of a function"; 1125 return true; 1126 } 1127 case MemRegion::BlockTextRegionKind: 1128 os << "block text"; 1129 return true; 1130 case MemRegion::BlockDataRegionKind: 1131 // FIXME: where the block came from? 1132 os << "a block"; 1133 return true; 1134 default: { 1135 const MemSpaceRegion *MS = MR->getMemorySpace(); 1136 1137 if (isa<StackLocalsSpaceRegion>(MS)) { 1138 const VarRegion *VR = dyn_cast<VarRegion>(MR); 1139 const VarDecl *VD; 1140 if (VR) 1141 VD = VR->getDecl(); 1142 else 1143 VD = NULL; 1144 1145 if (VD) 1146 os << "the address of the local variable '" << VD->getName() << "'"; 1147 else 1148 os << "the address of a local stack variable"; 1149 return true; 1150 } 1151 1152 if (isa<StackArgumentsSpaceRegion>(MS)) { 1153 const VarRegion *VR = dyn_cast<VarRegion>(MR); 1154 const VarDecl *VD; 1155 if (VR) 1156 VD = VR->getDecl(); 1157 else 1158 VD = NULL; 1159 1160 if (VD) 1161 os << "the address of the parameter '" << VD->getName() << "'"; 1162 else 1163 os << "the address of a parameter"; 1164 return true; 1165 } 1166 1167 if (isa<GlobalsSpaceRegion>(MS)) { 1168 const VarRegion *VR = dyn_cast<VarRegion>(MR); 1169 const VarDecl *VD; 1170 if (VR) 1171 VD = VR->getDecl(); 1172 else 1173 VD = NULL; 1174 1175 if (VD) { 1176 if (VD->isStaticLocal()) 1177 os << "the address of the static variable '" << VD->getName() << "'"; 1178 else 1179 os << "the address of the global variable '" << VD->getName() << "'"; 1180 } else 1181 os << "the address of a global variable"; 1182 return true; 1183 } 1184 1185 return false; 1186 } 1187 } 1188} 1189 1190void MallocChecker::ReportBadFree(CheckerContext &C, SVal ArgVal, 1191 SourceRange Range, 1192 const Expr *DeallocExpr) const { 1193 1194 if (!Filter.CMallocOptimistic && !Filter.CMallocPessimistic && 1195 !Filter.CNewDeleteChecker) 1196 return; 1197 1198 if (!isTrackedFamily(C, DeallocExpr)) 1199 return; 1200 1201 if (ExplodedNode *N = C.generateSink()) { 1202 if (!BT_BadFree) 1203 BT_BadFree.reset(new BugType("Bad free", "Memory Error")); 1204 1205 SmallString<100> buf; 1206 llvm::raw_svector_ostream os(buf); 1207 1208 const MemRegion *MR = ArgVal.getAsRegion(); 1209 while (const ElementRegion *ER = dyn_cast_or_null<ElementRegion>(MR)) 1210 MR = ER->getSuperRegion(); 1211 1212 if (MR && isa<AllocaRegion>(MR)) 1213 os << "Memory allocated by alloca() should not be deallocated"; 1214 else { 1215 os << "Argument to "; 1216 if (!printAllocDeallocName(os, C, DeallocExpr)) 1217 os << "deallocator"; 1218 1219 os << " is "; 1220 bool Summarized = MR ? SummarizeRegion(os, MR) 1221 : SummarizeValue(os, ArgVal); 1222 if (Summarized) 1223 os << ", which is not memory allocated by "; 1224 else 1225 os << "not memory allocated by "; 1226 1227 printExpectedAllocName(os, C, DeallocExpr); 1228 } 1229 1230 BugReport *R = new BugReport(*BT_BadFree, os.str(), N); 1231 R->markInteresting(MR); 1232 R->addRange(Range); 1233 C.emitReport(R); 1234 } 1235} 1236 1237void MallocChecker::ReportMismatchedDealloc(CheckerContext &C, 1238 SourceRange Range, 1239 const Expr *DeallocExpr, 1240 const RefState *RS, 1241 SymbolRef Sym) const { 1242 1243 if (!Filter.CMismatchedDeallocatorChecker) 1244 return; 1245 1246 if (ExplodedNode *N = C.generateSink()) { 1247 if (!BT_MismatchedDealloc) 1248 BT_MismatchedDealloc.reset(new BugType("Bad deallocator", 1249 "Memory Error")); 1250 1251 SmallString<100> buf; 1252 llvm::raw_svector_ostream os(buf); 1253 1254 const Expr *AllocExpr = cast<Expr>(RS->getStmt()); 1255 SmallString<20> AllocBuf; 1256 llvm::raw_svector_ostream AllocOs(AllocBuf); 1257 SmallString<20> DeallocBuf; 1258 llvm::raw_svector_ostream DeallocOs(DeallocBuf); 1259 1260 os << "Memory"; 1261 if (printAllocDeallocName(AllocOs, C, AllocExpr)) 1262 os << " allocated by " << AllocOs.str(); 1263 1264 os << " should be deallocated by "; 1265 printExpectedDeallocName(os, RS->getAllocationFamily()); 1266 1267 if (printAllocDeallocName(DeallocOs, C, DeallocExpr)) 1268 os << ", not " << DeallocOs.str(); 1269 1270 BugReport *R = new BugReport(*BT_MismatchedDealloc, os.str(), N); 1271 R->markInteresting(Sym); 1272 R->addRange(Range); 1273 R->addVisitor(new MallocBugVisitor(Sym)); 1274 C.emitReport(R); 1275 } 1276} 1277 1278void MallocChecker::ReportOffsetFree(CheckerContext &C, SVal ArgVal, 1279 SourceRange Range, const Expr *DeallocExpr, 1280 const Expr *AllocExpr) const { 1281 1282 if (!Filter.CMallocOptimistic && !Filter.CMallocPessimistic && 1283 !Filter.CNewDeleteChecker) 1284 return; 1285 1286 if (!isTrackedFamily(C, AllocExpr)) 1287 return; 1288 1289 ExplodedNode *N = C.generateSink(); 1290 if (N == NULL) 1291 return; 1292 1293 if (!BT_OffsetFree) 1294 BT_OffsetFree.reset(new BugType("Offset free", "Memory Error")); 1295 1296 SmallString<100> buf; 1297 llvm::raw_svector_ostream os(buf); 1298 SmallString<20> AllocNameBuf; 1299 llvm::raw_svector_ostream AllocNameOs(AllocNameBuf); 1300 1301 const MemRegion *MR = ArgVal.getAsRegion(); 1302 assert(MR && "Only MemRegion based symbols can have offset free errors"); 1303 1304 RegionOffset Offset = MR->getAsOffset(); 1305 assert((Offset.isValid() && 1306 !Offset.hasSymbolicOffset() && 1307 Offset.getOffset() != 0) && 1308 "Only symbols with a valid offset can have offset free errors"); 1309 1310 int offsetBytes = Offset.getOffset() / C.getASTContext().getCharWidth(); 1311 1312 os << "Argument to "; 1313 if (!printAllocDeallocName(os, C, DeallocExpr)) 1314 os << "deallocator"; 1315 os << " is offset by " 1316 << offsetBytes 1317 << " " 1318 << ((abs(offsetBytes) > 1) ? "bytes" : "byte") 1319 << " from the start of "; 1320 if (AllocExpr && printAllocDeallocName(AllocNameOs, C, AllocExpr)) 1321 os << "memory allocated by " << AllocNameOs.str(); 1322 else 1323 os << "allocated memory"; 1324 1325 BugReport *R = new BugReport(*BT_OffsetFree, os.str(), N); 1326 R->markInteresting(MR->getBaseRegion()); 1327 R->addRange(Range); 1328 C.emitReport(R); 1329} 1330 1331void MallocChecker::ReportUseAfterFree(CheckerContext &C, SourceRange Range, 1332 SymbolRef Sym) const { 1333 1334 if (!Filter.CMallocOptimistic && !Filter.CMallocPessimistic && 1335 !Filter.CNewDeleteChecker) 1336 return; 1337 1338 if (!isTrackedFamily(C, Sym)) 1339 return; 1340 1341 if (ExplodedNode *N = C.generateSink()) { 1342 if (!BT_UseFree) 1343 BT_UseFree.reset(new BugType("Use-after-free", "Memory Error")); 1344 1345 BugReport *R = new BugReport(*BT_UseFree, 1346 "Use of memory after it is freed", N); 1347 1348 R->markInteresting(Sym); 1349 R->addRange(Range); 1350 R->addVisitor(new MallocBugVisitor(Sym)); 1351 C.emitReport(R); 1352 } 1353} 1354 1355void MallocChecker::ReportDoubleFree(CheckerContext &C, SourceRange Range, 1356 bool Released, SymbolRef Sym, 1357 SymbolRef PrevSym) const { 1358 1359 if (!Filter.CMallocOptimistic && !Filter.CMallocPessimistic && 1360 !Filter.CNewDeleteChecker) 1361 return; 1362 1363 if (!isTrackedFamily(C, Sym)) 1364 return; 1365 1366 if (ExplodedNode *N = C.generateSink()) { 1367 if (!BT_DoubleFree) 1368 BT_DoubleFree.reset(new BugType("Double free", "Memory Error")); 1369 1370 BugReport *R = new BugReport(*BT_DoubleFree, 1371 (Released ? "Attempt to free released memory" 1372 : "Attempt to free non-owned memory"), 1373 N); 1374 R->addRange(Range); 1375 R->markInteresting(Sym); 1376 if (PrevSym) 1377 R->markInteresting(PrevSym); 1378 R->addVisitor(new MallocBugVisitor(Sym)); 1379 C.emitReport(R); 1380 } 1381} 1382 1383ProgramStateRef MallocChecker::ReallocMem(CheckerContext &C, 1384 const CallExpr *CE, 1385 bool FreesOnFail) const { 1386 if (CE->getNumArgs() < 2) 1387 return 0; 1388 1389 ProgramStateRef state = C.getState(); 1390 const Expr *arg0Expr = CE->getArg(0); 1391 const LocationContext *LCtx = C.getLocationContext(); 1392 SVal Arg0Val = state->getSVal(arg0Expr, LCtx); 1393 if (!Arg0Val.getAs<DefinedOrUnknownSVal>()) 1394 return 0; 1395 DefinedOrUnknownSVal arg0Val = Arg0Val.castAs<DefinedOrUnknownSVal>(); 1396 1397 SValBuilder &svalBuilder = C.getSValBuilder(); 1398 1399 DefinedOrUnknownSVal PtrEQ = 1400 svalBuilder.evalEQ(state, arg0Val, svalBuilder.makeNull()); 1401 1402 // Get the size argument. If there is no size arg then give up. 1403 const Expr *Arg1 = CE->getArg(1); 1404 if (!Arg1) 1405 return 0; 1406 1407 // Get the value of the size argument. 1408 SVal Arg1ValG = state->getSVal(Arg1, LCtx); 1409 if (!Arg1ValG.getAs<DefinedOrUnknownSVal>()) 1410 return 0; 1411 DefinedOrUnknownSVal Arg1Val = Arg1ValG.castAs<DefinedOrUnknownSVal>(); 1412 1413 // Compare the size argument to 0. 1414 DefinedOrUnknownSVal SizeZero = 1415 svalBuilder.evalEQ(state, Arg1Val, 1416 svalBuilder.makeIntValWithPtrWidth(0, false)); 1417 1418 ProgramStateRef StatePtrIsNull, StatePtrNotNull; 1419 llvm::tie(StatePtrIsNull, StatePtrNotNull) = state->assume(PtrEQ); 1420 ProgramStateRef StateSizeIsZero, StateSizeNotZero; 1421 llvm::tie(StateSizeIsZero, StateSizeNotZero) = state->assume(SizeZero); 1422 // We only assume exceptional states if they are definitely true; if the 1423 // state is under-constrained, assume regular realloc behavior. 1424 bool PrtIsNull = StatePtrIsNull && !StatePtrNotNull; 1425 bool SizeIsZero = StateSizeIsZero && !StateSizeNotZero; 1426 1427 // If the ptr is NULL and the size is not 0, the call is equivalent to 1428 // malloc(size). 1429 if ( PrtIsNull && !SizeIsZero) { 1430 ProgramStateRef stateMalloc = MallocMemAux(C, CE, CE->getArg(1), 1431 UndefinedVal(), StatePtrIsNull); 1432 return stateMalloc; 1433 } 1434 1435 if (PrtIsNull && SizeIsZero) 1436 return 0; 1437 1438 // Get the from and to pointer symbols as in toPtr = realloc(fromPtr, size). 1439 assert(!PrtIsNull); 1440 SymbolRef FromPtr = arg0Val.getAsSymbol(); 1441 SVal RetVal = state->getSVal(CE, LCtx); 1442 SymbolRef ToPtr = RetVal.getAsSymbol(); 1443 if (!FromPtr || !ToPtr) 1444 return 0; 1445 1446 bool ReleasedAllocated = false; 1447 1448 // If the size is 0, free the memory. 1449 if (SizeIsZero) 1450 if (ProgramStateRef stateFree = FreeMemAux(C, CE, StateSizeIsZero, 0, 1451 false, ReleasedAllocated)){ 1452 // The semantics of the return value are: 1453 // If size was equal to 0, either NULL or a pointer suitable to be passed 1454 // to free() is returned. We just free the input pointer and do not add 1455 // any constrains on the output pointer. 1456 return stateFree; 1457 } 1458 1459 // Default behavior. 1460 if (ProgramStateRef stateFree = 1461 FreeMemAux(C, CE, state, 0, false, ReleasedAllocated)) { 1462 1463 ProgramStateRef stateRealloc = MallocMemAux(C, CE, CE->getArg(1), 1464 UnknownVal(), stateFree); 1465 if (!stateRealloc) 1466 return 0; 1467 1468 ReallocPairKind Kind = RPToBeFreedAfterFailure; 1469 if (FreesOnFail) 1470 Kind = RPIsFreeOnFailure; 1471 else if (!ReleasedAllocated) 1472 Kind = RPDoNotTrackAfterFailure; 1473 1474 // Record the info about the reallocated symbol so that we could properly 1475 // process failed reallocation. 1476 stateRealloc = stateRealloc->set<ReallocPairs>(ToPtr, 1477 ReallocPair(FromPtr, Kind)); 1478 // The reallocated symbol should stay alive for as long as the new symbol. 1479 C.getSymbolManager().addSymbolDependency(ToPtr, FromPtr); 1480 return stateRealloc; 1481 } 1482 return 0; 1483} 1484 1485ProgramStateRef MallocChecker::CallocMem(CheckerContext &C, const CallExpr *CE){ 1486 if (CE->getNumArgs() < 2) 1487 return 0; 1488 1489 ProgramStateRef state = C.getState(); 1490 SValBuilder &svalBuilder = C.getSValBuilder(); 1491 const LocationContext *LCtx = C.getLocationContext(); 1492 SVal count = state->getSVal(CE->getArg(0), LCtx); 1493 SVal elementSize = state->getSVal(CE->getArg(1), LCtx); 1494 SVal TotalSize = svalBuilder.evalBinOp(state, BO_Mul, count, elementSize, 1495 svalBuilder.getContext().getSizeType()); 1496 SVal zeroVal = svalBuilder.makeZeroVal(svalBuilder.getContext().CharTy); 1497 1498 return MallocMemAux(C, CE, TotalSize, zeroVal, state); 1499} 1500 1501LeakInfo 1502MallocChecker::getAllocationSite(const ExplodedNode *N, SymbolRef Sym, 1503 CheckerContext &C) const { 1504 const LocationContext *LeakContext = N->getLocationContext(); 1505 // Walk the ExplodedGraph backwards and find the first node that referred to 1506 // the tracked symbol. 1507 const ExplodedNode *AllocNode = N; 1508 const MemRegion *ReferenceRegion = 0; 1509 1510 while (N) { 1511 ProgramStateRef State = N->getState(); 1512 if (!State->get<RegionState>(Sym)) 1513 break; 1514 1515 // Find the most recent expression bound to the symbol in the current 1516 // context. 1517 if (!ReferenceRegion) { 1518 if (const MemRegion *MR = C.getLocationRegionIfPostStore(N)) { 1519 SVal Val = State->getSVal(MR); 1520 if (Val.getAsLocSymbol() == Sym) 1521 ReferenceRegion = MR; 1522 } 1523 } 1524 1525 // Allocation node, is the last node in the current context in which the 1526 // symbol was tracked. 1527 if (N->getLocationContext() == LeakContext) 1528 AllocNode = N; 1529 N = N->pred_empty() ? NULL : *(N->pred_begin()); 1530 } 1531 1532 return LeakInfo(AllocNode, ReferenceRegion); 1533} 1534 1535void MallocChecker::reportLeak(SymbolRef Sym, ExplodedNode *N, 1536 CheckerContext &C) const { 1537 1538 if (!Filter.CMallocOptimistic && !Filter.CMallocPessimistic && 1539 !Filter.CNewDeleteChecker) 1540 return; 1541 1542 if (!isTrackedFamily(C, Sym)) 1543 return; 1544 1545 assert(N); 1546 if (!BT_Leak) { 1547 BT_Leak.reset(new BugType("Memory leak", "Memory Error")); 1548 // Leaks should not be reported if they are post-dominated by a sink: 1549 // (1) Sinks are higher importance bugs. 1550 // (2) NoReturnFunctionChecker uses sink nodes to represent paths ending 1551 // with __noreturn functions such as assert() or exit(). We choose not 1552 // to report leaks on such paths. 1553 BT_Leak->setSuppressOnSink(true); 1554 } 1555 1556 // Most bug reports are cached at the location where they occurred. 1557 // With leaks, we want to unique them by the location where they were 1558 // allocated, and only report a single path. 1559 PathDiagnosticLocation LocUsedForUniqueing; 1560 const ExplodedNode *AllocNode = 0; 1561 const MemRegion *Region = 0; 1562 llvm::tie(AllocNode, Region) = getAllocationSite(N, Sym, C); 1563 1564 ProgramPoint P = AllocNode->getLocation(); 1565 const Stmt *AllocationStmt = 0; 1566 if (Optional<CallExitEnd> Exit = P.getAs<CallExitEnd>()) 1567 AllocationStmt = Exit->getCalleeContext()->getCallSite(); 1568 else if (Optional<StmtPoint> SP = P.getAs<StmtPoint>()) 1569 AllocationStmt = SP->getStmt(); 1570 if (AllocationStmt) 1571 LocUsedForUniqueing = PathDiagnosticLocation::createBegin(AllocationStmt, 1572 C.getSourceManager(), 1573 AllocNode->getLocationContext()); 1574 1575 SmallString<200> buf; 1576 llvm::raw_svector_ostream os(buf); 1577 os << "Memory is never released; potential leak"; 1578 if (Region && Region->canPrintPretty()) { 1579 os << " of memory pointed to by '"; 1580 Region->printPretty(os); 1581 os << '\''; 1582 } 1583 1584 BugReport *R = new BugReport(*BT_Leak, os.str(), N, 1585 LocUsedForUniqueing, 1586 AllocNode->getLocationContext()->getDecl()); 1587 R->markInteresting(Sym); 1588 R->addVisitor(new MallocBugVisitor(Sym, true)); 1589 C.emitReport(R); 1590} 1591 1592void MallocChecker::checkDeadSymbols(SymbolReaper &SymReaper, 1593 CheckerContext &C) const 1594{ 1595 if (!SymReaper.hasDeadSymbols()) 1596 return; 1597 1598 ProgramStateRef state = C.getState(); 1599 RegionStateTy RS = state->get<RegionState>(); 1600 RegionStateTy::Factory &F = state->get_context<RegionState>(); 1601 1602 SmallVector<SymbolRef, 2> Errors; 1603 for (RegionStateTy::iterator I = RS.begin(), E = RS.end(); I != E; ++I) { 1604 if (SymReaper.isDead(I->first)) { 1605 if (I->second.isAllocated()) 1606 Errors.push_back(I->first); 1607 // Remove the dead symbol from the map. 1608 RS = F.remove(RS, I->first); 1609 1610 } 1611 } 1612 1613 // Cleanup the Realloc Pairs Map. 1614 ReallocPairsTy RP = state->get<ReallocPairs>(); 1615 for (ReallocPairsTy::iterator I = RP.begin(), E = RP.end(); I != E; ++I) { 1616 if (SymReaper.isDead(I->first) || 1617 SymReaper.isDead(I->second.ReallocatedSym)) { 1618 state = state->remove<ReallocPairs>(I->first); 1619 } 1620 } 1621 1622 // Cleanup the FreeReturnValue Map. 1623 FreeReturnValueTy FR = state->get<FreeReturnValue>(); 1624 for (FreeReturnValueTy::iterator I = FR.begin(), E = FR.end(); I != E; ++I) { 1625 if (SymReaper.isDead(I->first) || 1626 SymReaper.isDead(I->second)) { 1627 state = state->remove<FreeReturnValue>(I->first); 1628 } 1629 } 1630 1631 // Generate leak node. 1632 ExplodedNode *N = C.getPredecessor(); 1633 if (!Errors.empty()) { 1634 static SimpleProgramPointTag Tag("MallocChecker : DeadSymbolsLeak"); 1635 N = C.addTransition(C.getState(), C.getPredecessor(), &Tag); 1636 for (SmallVector<SymbolRef, 2>::iterator 1637 I = Errors.begin(), E = Errors.end(); I != E; ++I) { 1638 reportLeak(*I, N, C); 1639 } 1640 } 1641 1642 C.addTransition(state->set<RegionState>(RS), N); 1643} 1644 1645void MallocChecker::checkPreStmt(const CallExpr *CE, CheckerContext &C) const { 1646 // We will check for double free in the post visit. 1647 if ((Filter.CMallocOptimistic || Filter.CMallocPessimistic) && 1648 isFreeFunction(C.getCalleeDecl(CE), C.getASTContext())) 1649 return; 1650 1651 if (Filter.CNewDeleteChecker && 1652 isStandardNewDelete(C.getCalleeDecl(CE), C.getASTContext())) 1653 return; 1654 1655 // Check use after free, when a freed pointer is passed to a call. 1656 ProgramStateRef State = C.getState(); 1657 for (CallExpr::const_arg_iterator I = CE->arg_begin(), 1658 E = CE->arg_end(); I != E; ++I) { 1659 const Expr *A = *I; 1660 if (A->getType().getTypePtr()->isAnyPointerType()) { 1661 SymbolRef Sym = C.getSVal(A).getAsSymbol(); 1662 if (!Sym) 1663 continue; 1664 if (checkUseAfterFree(Sym, C, A)) 1665 return; 1666 } 1667 } 1668} 1669 1670void MallocChecker::checkPreStmt(const ReturnStmt *S, CheckerContext &C) const { 1671 const Expr *E = S->getRetValue(); 1672 if (!E) 1673 return; 1674 1675 // Check if we are returning a symbol. 1676 ProgramStateRef State = C.getState(); 1677 SVal RetVal = State->getSVal(E, C.getLocationContext()); 1678 SymbolRef Sym = RetVal.getAsSymbol(); 1679 if (!Sym) 1680 // If we are returning a field of the allocated struct or an array element, 1681 // the callee could still free the memory. 1682 // TODO: This logic should be a part of generic symbol escape callback. 1683 if (const MemRegion *MR = RetVal.getAsRegion()) 1684 if (isa<FieldRegion>(MR) || isa<ElementRegion>(MR)) 1685 if (const SymbolicRegion *BMR = 1686 dyn_cast<SymbolicRegion>(MR->getBaseRegion())) 1687 Sym = BMR->getSymbol(); 1688 1689 // Check if we are returning freed memory. 1690 if (Sym) 1691 checkUseAfterFree(Sym, C, E); 1692} 1693 1694// TODO: Blocks should be either inlined or should call invalidate regions 1695// upon invocation. After that's in place, special casing here will not be 1696// needed. 1697void MallocChecker::checkPostStmt(const BlockExpr *BE, 1698 CheckerContext &C) const { 1699 1700 // Scan the BlockDecRefExprs for any object the retain count checker 1701 // may be tracking. 1702 if (!BE->getBlockDecl()->hasCaptures()) 1703 return; 1704 1705 ProgramStateRef state = C.getState(); 1706 const BlockDataRegion *R = 1707 cast<BlockDataRegion>(state->getSVal(BE, 1708 C.getLocationContext()).getAsRegion()); 1709 1710 BlockDataRegion::referenced_vars_iterator I = R->referenced_vars_begin(), 1711 E = R->referenced_vars_end(); 1712 1713 if (I == E) 1714 return; 1715 1716 SmallVector<const MemRegion*, 10> Regions; 1717 const LocationContext *LC = C.getLocationContext(); 1718 MemRegionManager &MemMgr = C.getSValBuilder().getRegionManager(); 1719 1720 for ( ; I != E; ++I) { 1721 const VarRegion *VR = I.getCapturedRegion(); 1722 if (VR->getSuperRegion() == R) { 1723 VR = MemMgr.getVarRegion(VR->getDecl(), LC); 1724 } 1725 Regions.push_back(VR); 1726 } 1727 1728 state = 1729 state->scanReachableSymbols<StopTrackingCallback>(Regions.data(), 1730 Regions.data() + Regions.size()).getState(); 1731 C.addTransition(state); 1732} 1733 1734bool MallocChecker::isReleased(SymbolRef Sym, CheckerContext &C) const { 1735 assert(Sym); 1736 const RefState *RS = C.getState()->get<RegionState>(Sym); 1737 return (RS && RS->isReleased()); 1738} 1739 1740bool MallocChecker::checkUseAfterFree(SymbolRef Sym, CheckerContext &C, 1741 const Stmt *S) const { 1742 1743 if (isReleased(Sym, C)) { 1744 ReportUseAfterFree(C, S->getSourceRange(), Sym); 1745 return true; 1746 } 1747 1748 return false; 1749} 1750 1751// Check if the location is a freed symbolic region. 1752void MallocChecker::checkLocation(SVal l, bool isLoad, const Stmt *S, 1753 CheckerContext &C) const { 1754 SymbolRef Sym = l.getLocSymbolInBase(); 1755 if (Sym) 1756 checkUseAfterFree(Sym, C, S); 1757} 1758 1759// If a symbolic region is assumed to NULL (or another constant), stop tracking 1760// it - assuming that allocation failed on this path. 1761ProgramStateRef MallocChecker::evalAssume(ProgramStateRef state, 1762 SVal Cond, 1763 bool Assumption) const { 1764 RegionStateTy RS = state->get<RegionState>(); 1765 for (RegionStateTy::iterator I = RS.begin(), E = RS.end(); I != E; ++I) { 1766 // If the symbol is assumed to be NULL, remove it from consideration. 1767 ConstraintManager &CMgr = state->getConstraintManager(); 1768 ConditionTruthVal AllocFailed = CMgr.isNull(state, I.getKey()); 1769 if (AllocFailed.isConstrainedTrue()) 1770 state = state->remove<RegionState>(I.getKey()); 1771 } 1772 1773 // Realloc returns 0 when reallocation fails, which means that we should 1774 // restore the state of the pointer being reallocated. 1775 ReallocPairsTy RP = state->get<ReallocPairs>(); 1776 for (ReallocPairsTy::iterator I = RP.begin(), E = RP.end(); I != E; ++I) { 1777 // If the symbol is assumed to be NULL, remove it from consideration. 1778 ConstraintManager &CMgr = state->getConstraintManager(); 1779 ConditionTruthVal AllocFailed = CMgr.isNull(state, I.getKey()); 1780 if (!AllocFailed.isConstrainedTrue()) 1781 continue; 1782 1783 SymbolRef ReallocSym = I.getData().ReallocatedSym; 1784 if (const RefState *RS = state->get<RegionState>(ReallocSym)) { 1785 if (RS->isReleased()) { 1786 if (I.getData().Kind == RPToBeFreedAfterFailure) 1787 state = state->set<RegionState>(ReallocSym, 1788 RefState::getAllocated(RS->getAllocationFamily(), RS->getStmt())); 1789 else if (I.getData().Kind == RPDoNotTrackAfterFailure) 1790 state = state->remove<RegionState>(ReallocSym); 1791 else 1792 assert(I.getData().Kind == RPIsFreeOnFailure); 1793 } 1794 } 1795 state = state->remove<ReallocPairs>(I.getKey()); 1796 } 1797 1798 return state; 1799} 1800 1801bool MallocChecker::doesNotFreeMemOrInteresting(const CallEvent *Call, 1802 ProgramStateRef State) const { 1803 assert(Call); 1804 1805 // For now, assume that any C++ call can free memory. 1806 // TODO: If we want to be more optimistic here, we'll need to make sure that 1807 // regions escape to C++ containers. They seem to do that even now, but for 1808 // mysterious reasons. 1809 if (!(isa<FunctionCall>(Call) || isa<ObjCMethodCall>(Call))) 1810 return false; 1811 1812 // Check Objective-C messages by selector name. 1813 if (const ObjCMethodCall *Msg = dyn_cast<ObjCMethodCall>(Call)) { 1814 // If it's not a framework call, or if it takes a callback, assume it 1815 // can free memory. 1816 if (!Call->isInSystemHeader() || Call->hasNonZeroCallbackArg()) 1817 return false; 1818 1819 // If it's a method we know about, handle it explicitly post-call. 1820 // This should happen before the "freeWhenDone" check below. 1821 if (isKnownDeallocObjCMethodName(*Msg)) 1822 return true; 1823 1824 // If there's a "freeWhenDone" parameter, but the method isn't one we know 1825 // about, we can't be sure that the object will use free() to deallocate the 1826 // memory, so we can't model it explicitly. The best we can do is use it to 1827 // decide whether the pointer escapes. 1828 if (Optional<bool> FreeWhenDone = getFreeWhenDoneArg(*Msg)) 1829 return !*FreeWhenDone; 1830 1831 // If the first selector piece ends with "NoCopy", and there is no 1832 // "freeWhenDone" parameter set to zero, we know ownership is being 1833 // transferred. Again, though, we can't be sure that the object will use 1834 // free() to deallocate the memory, so we can't model it explicitly. 1835 StringRef FirstSlot = Msg->getSelector().getNameForSlot(0); 1836 if (FirstSlot.endswith("NoCopy")) 1837 return false; 1838 1839 // If the first selector starts with addPointer, insertPointer, 1840 // or replacePointer, assume we are dealing with NSPointerArray or similar. 1841 // This is similar to C++ containers (vector); we still might want to check 1842 // that the pointers get freed by following the container itself. 1843 if (FirstSlot.startswith("addPointer") || 1844 FirstSlot.startswith("insertPointer") || 1845 FirstSlot.startswith("replacePointer")) { 1846 return false; 1847 } 1848 1849 // Otherwise, assume that the method does not free memory. 1850 // Most framework methods do not free memory. 1851 return true; 1852 } 1853 1854 // At this point the only thing left to handle is straight function calls. 1855 const FunctionDecl *FD = cast<FunctionCall>(Call)->getDecl(); 1856 if (!FD) 1857 return false; 1858 1859 ASTContext &ASTC = State->getStateManager().getContext(); 1860 1861 // If it's one of the allocation functions we can reason about, we model 1862 // its behavior explicitly. 1863 if (isMemFunction(FD, ASTC)) 1864 return true; 1865 1866 // If it's not a system call, assume it frees memory. 1867 if (!Call->isInSystemHeader()) 1868 return false; 1869 1870 // White list the system functions whose arguments escape. 1871 const IdentifierInfo *II = FD->getIdentifier(); 1872 if (!II) 1873 return false; 1874 StringRef FName = II->getName(); 1875 1876 // White list the 'XXXNoCopy' CoreFoundation functions. 1877 // We specifically check these before 1878 if (FName.endswith("NoCopy")) { 1879 // Look for the deallocator argument. We know that the memory ownership 1880 // is not transferred only if the deallocator argument is 1881 // 'kCFAllocatorNull'. 1882 for (unsigned i = 1; i < Call->getNumArgs(); ++i) { 1883 const Expr *ArgE = Call->getArgExpr(i)->IgnoreParenCasts(); 1884 if (const DeclRefExpr *DE = dyn_cast<DeclRefExpr>(ArgE)) { 1885 StringRef DeallocatorName = DE->getFoundDecl()->getName(); 1886 if (DeallocatorName == "kCFAllocatorNull") 1887 return true; 1888 } 1889 } 1890 return false; 1891 } 1892 1893 // Associating streams with malloced buffers. The pointer can escape if 1894 // 'closefn' is specified (and if that function does free memory), 1895 // but it will not if closefn is not specified. 1896 // Currently, we do not inspect the 'closefn' function (PR12101). 1897 if (FName == "funopen") 1898 if (Call->getNumArgs() >= 4 && Call->getArgSVal(4).isConstant(0)) 1899 return true; 1900 1901 // Do not warn on pointers passed to 'setbuf' when used with std streams, 1902 // these leaks might be intentional when setting the buffer for stdio. 1903 // http://stackoverflow.com/questions/2671151/who-frees-setvbuf-buffer 1904 if (FName == "setbuf" || FName =="setbuffer" || 1905 FName == "setlinebuf" || FName == "setvbuf") { 1906 if (Call->getNumArgs() >= 1) { 1907 const Expr *ArgE = Call->getArgExpr(0)->IgnoreParenCasts(); 1908 if (const DeclRefExpr *ArgDRE = dyn_cast<DeclRefExpr>(ArgE)) 1909 if (const VarDecl *D = dyn_cast<VarDecl>(ArgDRE->getDecl())) 1910 if (D->getCanonicalDecl()->getName().find("std") != StringRef::npos) 1911 return false; 1912 } 1913 } 1914 1915 // A bunch of other functions which either take ownership of a pointer or 1916 // wrap the result up in a struct or object, meaning it can be freed later. 1917 // (See RetainCountChecker.) Not all the parameters here are invalidated, 1918 // but the Malloc checker cannot differentiate between them. The right way 1919 // of doing this would be to implement a pointer escapes callback. 1920 if (FName == "CGBitmapContextCreate" || 1921 FName == "CGBitmapContextCreateWithData" || 1922 FName == "CVPixelBufferCreateWithBytes" || 1923 FName == "CVPixelBufferCreateWithPlanarBytes" || 1924 FName == "OSAtomicEnqueue") { 1925 return false; 1926 } 1927 1928 // Handle cases where we know a buffer's /address/ can escape. 1929 // Note that the above checks handle some special cases where we know that 1930 // even though the address escapes, it's still our responsibility to free the 1931 // buffer. 1932 if (Call->argumentsMayEscape()) 1933 return false; 1934 1935 // Otherwise, assume that the function does not free memory. 1936 // Most system calls do not free the memory. 1937 return true; 1938} 1939 1940static bool retTrue(const RefState *RS) { 1941 return true; 1942} 1943 1944static bool checkIfNewOrNewArrayFamily(const RefState *RS) { 1945 return (RS->getAllocationFamily() == AF_CXXNewArray || 1946 RS->getAllocationFamily() == AF_CXXNew); 1947} 1948 1949ProgramStateRef MallocChecker::checkPointerEscape(ProgramStateRef State, 1950 const InvalidatedSymbols &Escaped, 1951 const CallEvent *Call, 1952 PointerEscapeKind Kind) const { 1953 return checkPointerEscapeAux(State, Escaped, Call, Kind, &retTrue); 1954} 1955 1956ProgramStateRef MallocChecker::checkConstPointerEscape(ProgramStateRef State, 1957 const InvalidatedSymbols &Escaped, 1958 const CallEvent *Call, 1959 PointerEscapeKind Kind) const { 1960 return checkPointerEscapeAux(State, Escaped, Call, Kind, 1961 &checkIfNewOrNewArrayFamily); 1962} 1963 1964ProgramStateRef MallocChecker::checkPointerEscapeAux(ProgramStateRef State, 1965 const InvalidatedSymbols &Escaped, 1966 const CallEvent *Call, 1967 PointerEscapeKind Kind, 1968 bool(*CheckRefState)(const RefState*)) const { 1969 // If we know that the call does not free memory, or we want to process the 1970 // call later, keep tracking the top level arguments. 1971 if ((Kind == PSK_DirectEscapeOnCall || 1972 Kind == PSK_IndirectEscapeOnCall) && 1973 doesNotFreeMemOrInteresting(Call, State)) { 1974 return State; 1975 } 1976 1977 for (InvalidatedSymbols::const_iterator I = Escaped.begin(), 1978 E = Escaped.end(); 1979 I != E; ++I) { 1980 SymbolRef sym = *I; 1981 1982 if (const RefState *RS = State->get<RegionState>(sym)) { 1983 if (RS->isAllocated() && CheckRefState(RS)) 1984 State = State->remove<RegionState>(sym); 1985 } 1986 } 1987 return State; 1988} 1989 1990static SymbolRef findFailedReallocSymbol(ProgramStateRef currState, 1991 ProgramStateRef prevState) { 1992 ReallocPairsTy currMap = currState->get<ReallocPairs>(); 1993 ReallocPairsTy prevMap = prevState->get<ReallocPairs>(); 1994 1995 for (ReallocPairsTy::iterator I = prevMap.begin(), E = prevMap.end(); 1996 I != E; ++I) { 1997 SymbolRef sym = I.getKey(); 1998 if (!currMap.lookup(sym)) 1999 return sym; 2000 } 2001 2002 return NULL; 2003} 2004 2005PathDiagnosticPiece * 2006MallocChecker::MallocBugVisitor::VisitNode(const ExplodedNode *N, 2007 const ExplodedNode *PrevN, 2008 BugReporterContext &BRC, 2009 BugReport &BR) { 2010 ProgramStateRef state = N->getState(); 2011 ProgramStateRef statePrev = PrevN->getState(); 2012 2013 const RefState *RS = state->get<RegionState>(Sym); 2014 const RefState *RSPrev = statePrev->get<RegionState>(Sym); 2015 if (!RS) 2016 return 0; 2017 2018 const Stmt *S = 0; 2019 const char *Msg = 0; 2020 StackHintGeneratorForSymbol *StackHint = 0; 2021 2022 // Retrieve the associated statement. 2023 ProgramPoint ProgLoc = N->getLocation(); 2024 if (Optional<StmtPoint> SP = ProgLoc.getAs<StmtPoint>()) { 2025 S = SP->getStmt(); 2026 } else if (Optional<CallExitEnd> Exit = ProgLoc.getAs<CallExitEnd>()) { 2027 S = Exit->getCalleeContext()->getCallSite(); 2028 } else if (Optional<BlockEdge> Edge = ProgLoc.getAs<BlockEdge>()) { 2029 // If an assumption was made on a branch, it should be caught 2030 // here by looking at the state transition. 2031 S = Edge->getSrc()->getTerminator(); 2032 } 2033 2034 if (!S) 2035 return 0; 2036 2037 // FIXME: We will eventually need to handle non-statement-based events 2038 // (__attribute__((cleanup))). 2039 2040 // Find out if this is an interesting point and what is the kind. 2041 if (Mode == Normal) { 2042 if (isAllocated(RS, RSPrev, S)) { 2043 Msg = "Memory is allocated"; 2044 StackHint = new StackHintGeneratorForSymbol(Sym, 2045 "Returned allocated memory"); 2046 } else if (isReleased(RS, RSPrev, S)) { 2047 Msg = "Memory is released"; 2048 StackHint = new StackHintGeneratorForSymbol(Sym, 2049 "Returned released memory"); 2050 } else if (isRelinquished(RS, RSPrev, S)) { 2051 Msg = "Memory ownership is transfered"; 2052 StackHint = new StackHintGeneratorForSymbol(Sym, ""); 2053 } else if (isReallocFailedCheck(RS, RSPrev, S)) { 2054 Mode = ReallocationFailed; 2055 Msg = "Reallocation failed"; 2056 StackHint = new StackHintGeneratorForReallocationFailed(Sym, 2057 "Reallocation failed"); 2058 2059 if (SymbolRef sym = findFailedReallocSymbol(state, statePrev)) { 2060 // Is it possible to fail two reallocs WITHOUT testing in between? 2061 assert((!FailedReallocSymbol || FailedReallocSymbol == sym) && 2062 "We only support one failed realloc at a time."); 2063 BR.markInteresting(sym); 2064 FailedReallocSymbol = sym; 2065 } 2066 } 2067 2068 // We are in a special mode if a reallocation failed later in the path. 2069 } else if (Mode == ReallocationFailed) { 2070 assert(FailedReallocSymbol && "No symbol to look for."); 2071 2072 // Is this is the first appearance of the reallocated symbol? 2073 if (!statePrev->get<RegionState>(FailedReallocSymbol)) { 2074 // We're at the reallocation point. 2075 Msg = "Attempt to reallocate memory"; 2076 StackHint = new StackHintGeneratorForSymbol(Sym, 2077 "Returned reallocated memory"); 2078 FailedReallocSymbol = NULL; 2079 Mode = Normal; 2080 } 2081 } 2082 2083 if (!Msg) 2084 return 0; 2085 assert(StackHint); 2086 2087 // Generate the extra diagnostic. 2088 PathDiagnosticLocation Pos(S, BRC.getSourceManager(), 2089 N->getLocationContext()); 2090 return new PathDiagnosticEventPiece(Pos, Msg, true, StackHint); 2091} 2092 2093void MallocChecker::printState(raw_ostream &Out, ProgramStateRef State, 2094 const char *NL, const char *Sep) const { 2095 2096 RegionStateTy RS = State->get<RegionState>(); 2097 2098 if (!RS.isEmpty()) { 2099 Out << Sep << "MallocChecker:" << NL; 2100 for (RegionStateTy::iterator I = RS.begin(), E = RS.end(); I != E; ++I) { 2101 I.getKey()->dumpToStream(Out); 2102 Out << " : "; 2103 I.getData().dump(Out); 2104 Out << NL; 2105 } 2106 } 2107} 2108 2109#define REGISTER_CHECKER(name) \ 2110void ento::register##name(CheckerManager &mgr) {\ 2111 registerCStringCheckerBasic(mgr); \ 2112 mgr.registerChecker<MallocChecker>()->Filter.C##name = true;\ 2113} 2114 2115REGISTER_CHECKER(MallocPessimistic) 2116REGISTER_CHECKER(MallocOptimistic) 2117REGISTER_CHECKER(NewDeleteChecker) 2118REGISTER_CHECKER(MismatchedDeallocatorChecker) 2119