MallocChecker.cpp revision fb7f76f285faa4c21d299f2bce8f55de3f71e548
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/StaticAnalyzer/Core/Checker.h" 18#include "clang/StaticAnalyzer/Core/CheckerManager.h" 19#include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h" 20#include "clang/StaticAnalyzer/Core/BugReporter/BugType.h" 21#include "clang/StaticAnalyzer/Core/PathSensitive/ObjCMessage.h" 22#include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h" 23#include "clang/StaticAnalyzer/Core/PathSensitive/ProgramStateTrait.h" 24#include "clang/StaticAnalyzer/Core/PathSensitive/SymbolManager.h" 25#include "clang/Basic/SourceManager.h" 26#include "llvm/ADT/ImmutableMap.h" 27#include "llvm/ADT/SmallString.h" 28#include "llvm/ADT/STLExtras.h" 29#include <climits> 30 31using namespace clang; 32using namespace ento; 33 34namespace { 35 36class RefState { 37 enum Kind { AllocateUnchecked, AllocateFailed, Released, Escaped, 38 Relinquished } K; 39 const Stmt *S; 40 41public: 42 RefState(Kind k, const Stmt *s) : K(k), S(s) {} 43 44 bool isAllocated() const { return K == AllocateUnchecked; } 45 bool isReleased() const { return K == Released; } 46 47 const Stmt *getStmt() const { return S; } 48 49 bool operator==(const RefState &X) const { 50 return K == X.K && S == X.S; 51 } 52 53 static RefState getAllocateUnchecked(const Stmt *s) { 54 return RefState(AllocateUnchecked, s); 55 } 56 static RefState getAllocateFailed() { 57 return RefState(AllocateFailed, 0); 58 } 59 static RefState getReleased(const Stmt *s) { return RefState(Released, s); } 60 static RefState getEscaped(const Stmt *s) { return RefState(Escaped, s); } 61 static RefState getRelinquished(const Stmt *s) { 62 return RefState(Relinquished, s); 63 } 64 65 void Profile(llvm::FoldingSetNodeID &ID) const { 66 ID.AddInteger(K); 67 ID.AddPointer(S); 68 } 69}; 70 71struct ReallocPair { 72 SymbolRef ReallocatedSym; 73 bool IsFreeOnFailure; 74 ReallocPair(SymbolRef S, bool F) : ReallocatedSym(S), IsFreeOnFailure(F) {} 75 void Profile(llvm::FoldingSetNodeID &ID) const { 76 ID.AddInteger(IsFreeOnFailure); 77 ID.AddPointer(ReallocatedSym); 78 } 79 bool operator==(const ReallocPair &X) const { 80 return ReallocatedSym == X.ReallocatedSym && 81 IsFreeOnFailure == X.IsFreeOnFailure; 82 } 83}; 84 85class MallocChecker : public Checker<check::DeadSymbols, 86 check::EndPath, 87 check::PreStmt<ReturnStmt>, 88 check::PreStmt<CallExpr>, 89 check::PostStmt<CallExpr>, 90 check::Location, 91 check::Bind, 92 eval::Assume, 93 check::RegionChanges> 94{ 95 mutable OwningPtr<BugType> BT_DoubleFree; 96 mutable OwningPtr<BugType> BT_Leak; 97 mutable OwningPtr<BugType> BT_UseFree; 98 mutable OwningPtr<BugType> BT_BadFree; 99 mutable IdentifierInfo *II_malloc, *II_free, *II_realloc, *II_calloc, 100 *II_valloc, *II_reallocf, *II_strndup, *II_strdup; 101 102 static const unsigned InvalidArgIndex = UINT_MAX; 103 104public: 105 MallocChecker() : II_malloc(0), II_free(0), II_realloc(0), II_calloc(0), 106 II_valloc(0), II_reallocf(0), II_strndup(0), II_strdup(0) {} 107 108 /// In pessimistic mode, the checker assumes that it does not know which 109 /// functions might free the memory. 110 struct ChecksFilter { 111 DefaultBool CMallocPessimistic; 112 DefaultBool CMallocOptimistic; 113 }; 114 115 ChecksFilter Filter; 116 117 void checkPreStmt(const CallExpr *S, CheckerContext &C) const; 118 void checkPostStmt(const CallExpr *CE, CheckerContext &C) const; 119 void checkDeadSymbols(SymbolReaper &SymReaper, CheckerContext &C) const; 120 void checkEndPath(CheckerContext &C) const; 121 void checkPreStmt(const ReturnStmt *S, CheckerContext &C) const; 122 ProgramStateRef evalAssume(ProgramStateRef state, SVal Cond, 123 bool Assumption) const; 124 void checkLocation(SVal l, bool isLoad, const Stmt *S, 125 CheckerContext &C) const; 126 void checkBind(SVal location, SVal val, const Stmt*S, 127 CheckerContext &C) const; 128 ProgramStateRef 129 checkRegionChanges(ProgramStateRef state, 130 const StoreManager::InvalidatedSymbols *invalidated, 131 ArrayRef<const MemRegion *> ExplicitRegions, 132 ArrayRef<const MemRegion *> Regions, 133 const CallOrObjCMessage *Call) const; 134 bool wantsRegionChangeUpdate(ProgramStateRef state) const { 135 return true; 136 } 137 138private: 139 void initIdentifierInfo(ASTContext &C) const; 140 141 /// Check if this is one of the functions which can allocate/reallocate memory 142 /// pointed to by one of its arguments. 143 bool isMemFunction(const FunctionDecl *FD, ASTContext &C) const; 144 145 static ProgramStateRef MallocMemReturnsAttr(CheckerContext &C, 146 const CallExpr *CE, 147 const OwnershipAttr* Att); 148 static ProgramStateRef MallocMemAux(CheckerContext &C, const CallExpr *CE, 149 const Expr *SizeEx, SVal Init, 150 ProgramStateRef state) { 151 return MallocMemAux(C, CE, 152 state->getSVal(SizeEx, C.getLocationContext()), 153 Init, state); 154 } 155 156 static ProgramStateRef MallocMemAux(CheckerContext &C, const CallExpr *CE, 157 SVal SizeEx, SVal Init, 158 ProgramStateRef state); 159 160 /// Update the RefState to reflect the new memory allocation. 161 static ProgramStateRef MallocUpdateRefState(CheckerContext &C, 162 const CallExpr *CE, 163 ProgramStateRef state); 164 165 ProgramStateRef FreeMemAttr(CheckerContext &C, const CallExpr *CE, 166 const OwnershipAttr* Att) const; 167 ProgramStateRef FreeMemAux(CheckerContext &C, const CallExpr *CE, 168 ProgramStateRef state, unsigned Num, 169 bool Hold) const; 170 171 ProgramStateRef ReallocMem(CheckerContext &C, const CallExpr *CE, 172 bool FreesMemOnFailure) const; 173 static ProgramStateRef CallocMem(CheckerContext &C, const CallExpr *CE); 174 175 bool checkEscape(SymbolRef Sym, const Stmt *S, CheckerContext &C) const; 176 bool checkUseAfterFree(SymbolRef Sym, CheckerContext &C, 177 const Stmt *S = 0) const; 178 179 /// Check if the function is not known to us. So, for example, we could 180 /// conservatively assume it can free/reallocate it's pointer arguments. 181 bool doesNotFreeMemory(const CallOrObjCMessage *Call, 182 ProgramStateRef State) const; 183 184 static bool SummarizeValue(raw_ostream &os, SVal V); 185 static bool SummarizeRegion(raw_ostream &os, const MemRegion *MR); 186 void ReportBadFree(CheckerContext &C, SVal ArgVal, SourceRange range) const; 187 188 /// Find the location of the allocation for Sym on the path leading to the 189 /// exploded node N. 190 const Stmt *getAllocationSite(const ExplodedNode *N, SymbolRef Sym, 191 CheckerContext &C) const; 192 193 void reportLeak(SymbolRef Sym, ExplodedNode *N, CheckerContext &C) const; 194 195 /// The bug visitor which allows us to print extra diagnostics along the 196 /// BugReport path. For example, showing the allocation site of the leaked 197 /// region. 198 class MallocBugVisitor : public BugReporterVisitor { 199 protected: 200 enum NotificationMode { 201 Normal, 202 Complete, 203 ReallocationFailed 204 }; 205 206 // The allocated region symbol tracked by the main analysis. 207 SymbolRef Sym; 208 NotificationMode Mode; 209 210 public: 211 MallocBugVisitor(SymbolRef S) : Sym(S), Mode(Normal) {} 212 virtual ~MallocBugVisitor() {} 213 214 void Profile(llvm::FoldingSetNodeID &ID) const { 215 static int X = 0; 216 ID.AddPointer(&X); 217 ID.AddPointer(Sym); 218 } 219 220 inline bool isAllocated(const RefState *S, const RefState *SPrev, 221 const Stmt *Stmt) { 222 // Did not track -> allocated. Other state (released) -> allocated. 223 return (Stmt && isa<CallExpr>(Stmt) && 224 (S && S->isAllocated()) && (!SPrev || !SPrev->isAllocated())); 225 } 226 227 inline bool isReleased(const RefState *S, const RefState *SPrev, 228 const Stmt *Stmt) { 229 // Did not track -> released. Other state (allocated) -> released. 230 return (Stmt && isa<CallExpr>(Stmt) && 231 (S && S->isReleased()) && (!SPrev || !SPrev->isReleased())); 232 } 233 234 inline bool isReallocFailedCheck(const RefState *S, const RefState *SPrev, 235 const Stmt *Stmt) { 236 // If the expression is not a call, and the state change is 237 // released -> allocated, it must be the realloc return value 238 // check. If we have to handle more cases here, it might be cleaner just 239 // to track this extra bit in the state itself. 240 return ((!Stmt || !isa<CallExpr>(Stmt)) && 241 (S && S->isAllocated()) && (SPrev && !SPrev->isAllocated())); 242 } 243 244 PathDiagnosticPiece *VisitNode(const ExplodedNode *N, 245 const ExplodedNode *PrevN, 246 BugReporterContext &BRC, 247 BugReport &BR); 248 }; 249}; 250} // end anonymous namespace 251 252typedef llvm::ImmutableMap<SymbolRef, RefState> RegionStateTy; 253typedef llvm::ImmutableMap<SymbolRef, ReallocPair > ReallocMap; 254class RegionState {}; 255class ReallocPairs {}; 256namespace clang { 257namespace ento { 258 template <> 259 struct ProgramStateTrait<RegionState> 260 : public ProgramStatePartialTrait<RegionStateTy> { 261 static void *GDMIndex() { static int x; return &x; } 262 }; 263 264 template <> 265 struct ProgramStateTrait<ReallocPairs> 266 : public ProgramStatePartialTrait<ReallocMap> { 267 static void *GDMIndex() { static int x; return &x; } 268 }; 269} 270} 271 272namespace { 273class StopTrackingCallback : public SymbolVisitor { 274 ProgramStateRef state; 275public: 276 StopTrackingCallback(ProgramStateRef st) : state(st) {} 277 ProgramStateRef getState() const { return state; } 278 279 bool VisitSymbol(SymbolRef sym) { 280 state = state->remove<RegionState>(sym); 281 return true; 282 } 283}; 284} // end anonymous namespace 285 286void MallocChecker::initIdentifierInfo(ASTContext &Ctx) const { 287 if (!II_malloc) 288 II_malloc = &Ctx.Idents.get("malloc"); 289 if (!II_free) 290 II_free = &Ctx.Idents.get("free"); 291 if (!II_realloc) 292 II_realloc = &Ctx.Idents.get("realloc"); 293 if (!II_reallocf) 294 II_reallocf = &Ctx.Idents.get("reallocf"); 295 if (!II_calloc) 296 II_calloc = &Ctx.Idents.get("calloc"); 297 if (!II_valloc) 298 II_valloc = &Ctx.Idents.get("valloc"); 299 if (!II_strdup) 300 II_strdup = &Ctx.Idents.get("strdup"); 301 if (!II_strndup) 302 II_strndup = &Ctx.Idents.get("strndup"); 303} 304 305bool MallocChecker::isMemFunction(const FunctionDecl *FD, ASTContext &C) const { 306 if (!FD) 307 return false; 308 IdentifierInfo *FunI = FD->getIdentifier(); 309 if (!FunI) 310 return false; 311 312 initIdentifierInfo(C); 313 314 if (FunI == II_malloc || FunI == II_free || FunI == II_realloc || 315 FunI == II_reallocf || FunI == II_calloc || FunI == II_valloc || 316 FunI == II_strdup || FunI == II_strndup) 317 return true; 318 319 if (Filter.CMallocOptimistic && FD->hasAttrs() && 320 FD->specific_attr_begin<OwnershipAttr>() != 321 FD->specific_attr_end<OwnershipAttr>()) 322 return true; 323 324 325 return false; 326} 327 328void MallocChecker::checkPostStmt(const CallExpr *CE, CheckerContext &C) const { 329 const FunctionDecl *FD = C.getCalleeDecl(CE); 330 if (!FD) 331 return; 332 333 initIdentifierInfo(C.getASTContext()); 334 IdentifierInfo *FunI = FD->getIdentifier(); 335 if (!FunI) 336 return; 337 338 ProgramStateRef State = C.getState(); 339 if (FunI == II_malloc || FunI == II_valloc) { 340 State = MallocMemAux(C, CE, CE->getArg(0), UndefinedVal(), State); 341 } else if (FunI == II_realloc) { 342 State = ReallocMem(C, CE, false); 343 } else if (FunI == II_reallocf) { 344 State = ReallocMem(C, CE, true); 345 } else if (FunI == II_calloc) { 346 State = CallocMem(C, CE); 347 } else if (FunI == II_free) { 348 State = FreeMemAux(C, CE, C.getState(), 0, false); 349 } else if (FunI == II_strdup) { 350 State = MallocUpdateRefState(C, CE, State); 351 } else if (FunI == II_strndup) { 352 State = MallocUpdateRefState(C, CE, State); 353 } else if (Filter.CMallocOptimistic) { 354 // Check all the attributes, if there are any. 355 // There can be multiple of these attributes. 356 if (FD->hasAttrs()) 357 for (specific_attr_iterator<OwnershipAttr> 358 i = FD->specific_attr_begin<OwnershipAttr>(), 359 e = FD->specific_attr_end<OwnershipAttr>(); 360 i != e; ++i) { 361 switch ((*i)->getOwnKind()) { 362 case OwnershipAttr::Returns: 363 State = MallocMemReturnsAttr(C, CE, *i); 364 break; 365 case OwnershipAttr::Takes: 366 case OwnershipAttr::Holds: 367 State = FreeMemAttr(C, CE, *i); 368 break; 369 } 370 } 371 } 372 C.addTransition(State); 373} 374 375ProgramStateRef MallocChecker::MallocMemReturnsAttr(CheckerContext &C, 376 const CallExpr *CE, 377 const OwnershipAttr* Att) { 378 if (Att->getModule() != "malloc") 379 return 0; 380 381 OwnershipAttr::args_iterator I = Att->args_begin(), E = Att->args_end(); 382 if (I != E) { 383 return MallocMemAux(C, CE, CE->getArg(*I), UndefinedVal(), C.getState()); 384 } 385 return MallocMemAux(C, CE, UnknownVal(), UndefinedVal(), C.getState()); 386} 387 388ProgramStateRef MallocChecker::MallocMemAux(CheckerContext &C, 389 const CallExpr *CE, 390 SVal Size, SVal Init, 391 ProgramStateRef state) { 392 // Get the return value. 393 SVal retVal = state->getSVal(CE, C.getLocationContext()); 394 395 // We expect the malloc functions to return a pointer. 396 if (!isa<Loc>(retVal)) 397 return 0; 398 399 // Fill the region with the initialization value. 400 state = state->bindDefault(retVal, Init); 401 402 // Set the region's extent equal to the Size parameter. 403 const SymbolicRegion *R = 404 dyn_cast_or_null<SymbolicRegion>(retVal.getAsRegion()); 405 if (!R) 406 return 0; 407 if (isa<DefinedOrUnknownSVal>(Size)) { 408 SValBuilder &svalBuilder = C.getSValBuilder(); 409 DefinedOrUnknownSVal Extent = R->getExtent(svalBuilder); 410 DefinedOrUnknownSVal DefinedSize = cast<DefinedOrUnknownSVal>(Size); 411 DefinedOrUnknownSVal extentMatchesSize = 412 svalBuilder.evalEQ(state, Extent, DefinedSize); 413 414 state = state->assume(extentMatchesSize, true); 415 assert(state); 416 } 417 418 return MallocUpdateRefState(C, CE, state); 419} 420 421ProgramStateRef MallocChecker::MallocUpdateRefState(CheckerContext &C, 422 const CallExpr *CE, 423 ProgramStateRef state) { 424 // Get the return value. 425 SVal retVal = state->getSVal(CE, C.getLocationContext()); 426 427 // We expect the malloc functions to return a pointer. 428 if (!isa<Loc>(retVal)) 429 return 0; 430 431 SymbolRef Sym = retVal.getAsLocSymbol(); 432 assert(Sym); 433 434 // Set the symbol's state to Allocated. 435 return state->set<RegionState>(Sym, RefState::getAllocateUnchecked(CE)); 436 437} 438 439ProgramStateRef MallocChecker::FreeMemAttr(CheckerContext &C, 440 const CallExpr *CE, 441 const OwnershipAttr* Att) const { 442 if (Att->getModule() != "malloc") 443 return 0; 444 445 ProgramStateRef State = C.getState(); 446 447 for (OwnershipAttr::args_iterator I = Att->args_begin(), E = Att->args_end(); 448 I != E; ++I) { 449 ProgramStateRef StateI = FreeMemAux(C, CE, State, *I, 450 Att->getOwnKind() == OwnershipAttr::Holds); 451 if (StateI) 452 State = StateI; 453 } 454 return State; 455} 456 457ProgramStateRef MallocChecker::FreeMemAux(CheckerContext &C, 458 const CallExpr *CE, 459 ProgramStateRef state, 460 unsigned Num, 461 bool Hold) const { 462 const Expr *ArgExpr = CE->getArg(Num); 463 SVal ArgVal = state->getSVal(ArgExpr, C.getLocationContext()); 464 if (!isa<DefinedOrUnknownSVal>(ArgVal)) 465 return 0; 466 DefinedOrUnknownSVal location = cast<DefinedOrUnknownSVal>(ArgVal); 467 468 // Check for null dereferences. 469 if (!isa<Loc>(location)) 470 return 0; 471 472 // The explicit NULL case, no operation is performed. 473 ProgramStateRef notNullState, nullState; 474 llvm::tie(notNullState, nullState) = state->assume(location); 475 if (nullState && !notNullState) 476 return 0; 477 478 // Unknown values could easily be okay 479 // Undefined values are handled elsewhere 480 if (ArgVal.isUnknownOrUndef()) 481 return 0; 482 483 const MemRegion *R = ArgVal.getAsRegion(); 484 485 // Nonlocs can't be freed, of course. 486 // Non-region locations (labels and fixed addresses) also shouldn't be freed. 487 if (!R) { 488 ReportBadFree(C, ArgVal, ArgExpr->getSourceRange()); 489 return 0; 490 } 491 492 R = R->StripCasts(); 493 494 // Blocks might show up as heap data, but should not be free()d 495 if (isa<BlockDataRegion>(R)) { 496 ReportBadFree(C, ArgVal, ArgExpr->getSourceRange()); 497 return 0; 498 } 499 500 const MemSpaceRegion *MS = R->getMemorySpace(); 501 502 // Parameters, locals, statics, and globals shouldn't be freed. 503 if (!(isa<UnknownSpaceRegion>(MS) || isa<HeapSpaceRegion>(MS))) { 504 // FIXME: at the time this code was written, malloc() regions were 505 // represented by conjured symbols, which are all in UnknownSpaceRegion. 506 // This means that there isn't actually anything from HeapSpaceRegion 507 // that should be freed, even though we allow it here. 508 // Of course, free() can work on memory allocated outside the current 509 // function, so UnknownSpaceRegion is always a possibility. 510 // False negatives are better than false positives. 511 512 ReportBadFree(C, ArgVal, ArgExpr->getSourceRange()); 513 return 0; 514 } 515 516 const SymbolicRegion *SR = dyn_cast<SymbolicRegion>(R); 517 // Various cases could lead to non-symbol values here. 518 // For now, ignore them. 519 if (!SR) 520 return 0; 521 522 SymbolRef Sym = SR->getSymbol(); 523 const RefState *RS = state->get<RegionState>(Sym); 524 525 // If the symbol has not been tracked, return. This is possible when free() is 526 // called on a pointer that does not get its pointee directly from malloc(). 527 // Full support of this requires inter-procedural analysis. 528 if (!RS) 529 return 0; 530 531 // Check double free. 532 if (RS->isReleased()) { 533 if (ExplodedNode *N = C.generateSink()) { 534 if (!BT_DoubleFree) 535 BT_DoubleFree.reset( 536 new BugType("Double free", "Memory Error")); 537 BugReport *R = new BugReport(*BT_DoubleFree, 538 "Attempt to free released memory", N); 539 R->addRange(ArgExpr->getSourceRange()); 540 R->addVisitor(new MallocBugVisitor(Sym)); 541 C.EmitReport(R); 542 } 543 return 0; 544 } 545 546 // Normal free. 547 if (Hold) 548 return state->set<RegionState>(Sym, RefState::getRelinquished(CE)); 549 return state->set<RegionState>(Sym, RefState::getReleased(CE)); 550} 551 552bool MallocChecker::SummarizeValue(raw_ostream &os, SVal V) { 553 if (nonloc::ConcreteInt *IntVal = dyn_cast<nonloc::ConcreteInt>(&V)) 554 os << "an integer (" << IntVal->getValue() << ")"; 555 else if (loc::ConcreteInt *ConstAddr = dyn_cast<loc::ConcreteInt>(&V)) 556 os << "a constant address (" << ConstAddr->getValue() << ")"; 557 else if (loc::GotoLabel *Label = dyn_cast<loc::GotoLabel>(&V)) 558 os << "the address of the label '" << Label->getLabel()->getName() << "'"; 559 else 560 return false; 561 562 return true; 563} 564 565bool MallocChecker::SummarizeRegion(raw_ostream &os, 566 const MemRegion *MR) { 567 switch (MR->getKind()) { 568 case MemRegion::FunctionTextRegionKind: { 569 const FunctionDecl *FD = cast<FunctionTextRegion>(MR)->getDecl(); 570 if (FD) 571 os << "the address of the function '" << *FD << '\''; 572 else 573 os << "the address of a function"; 574 return true; 575 } 576 case MemRegion::BlockTextRegionKind: 577 os << "block text"; 578 return true; 579 case MemRegion::BlockDataRegionKind: 580 // FIXME: where the block came from? 581 os << "a block"; 582 return true; 583 default: { 584 const MemSpaceRegion *MS = MR->getMemorySpace(); 585 586 if (isa<StackLocalsSpaceRegion>(MS)) { 587 const VarRegion *VR = dyn_cast<VarRegion>(MR); 588 const VarDecl *VD; 589 if (VR) 590 VD = VR->getDecl(); 591 else 592 VD = NULL; 593 594 if (VD) 595 os << "the address of the local variable '" << VD->getName() << "'"; 596 else 597 os << "the address of a local stack variable"; 598 return true; 599 } 600 601 if (isa<StackArgumentsSpaceRegion>(MS)) { 602 const VarRegion *VR = dyn_cast<VarRegion>(MR); 603 const VarDecl *VD; 604 if (VR) 605 VD = VR->getDecl(); 606 else 607 VD = NULL; 608 609 if (VD) 610 os << "the address of the parameter '" << VD->getName() << "'"; 611 else 612 os << "the address of a parameter"; 613 return true; 614 } 615 616 if (isa<GlobalsSpaceRegion>(MS)) { 617 const VarRegion *VR = dyn_cast<VarRegion>(MR); 618 const VarDecl *VD; 619 if (VR) 620 VD = VR->getDecl(); 621 else 622 VD = NULL; 623 624 if (VD) { 625 if (VD->isStaticLocal()) 626 os << "the address of the static variable '" << VD->getName() << "'"; 627 else 628 os << "the address of the global variable '" << VD->getName() << "'"; 629 } else 630 os << "the address of a global variable"; 631 return true; 632 } 633 634 return false; 635 } 636 } 637} 638 639void MallocChecker::ReportBadFree(CheckerContext &C, SVal ArgVal, 640 SourceRange range) const { 641 if (ExplodedNode *N = C.generateSink()) { 642 if (!BT_BadFree) 643 BT_BadFree.reset(new BugType("Bad free", "Memory Error")); 644 645 SmallString<100> buf; 646 llvm::raw_svector_ostream os(buf); 647 648 const MemRegion *MR = ArgVal.getAsRegion(); 649 if (MR) { 650 while (const ElementRegion *ER = dyn_cast<ElementRegion>(MR)) 651 MR = ER->getSuperRegion(); 652 653 // Special case for alloca() 654 if (isa<AllocaRegion>(MR)) 655 os << "Argument to free() was allocated by alloca(), not malloc()"; 656 else { 657 os << "Argument to free() is "; 658 if (SummarizeRegion(os, MR)) 659 os << ", which is not memory allocated by malloc()"; 660 else 661 os << "not memory allocated by malloc()"; 662 } 663 } else { 664 os << "Argument to free() is "; 665 if (SummarizeValue(os, ArgVal)) 666 os << ", which is not memory allocated by malloc()"; 667 else 668 os << "not memory allocated by malloc()"; 669 } 670 671 BugReport *R = new BugReport(*BT_BadFree, os.str(), N); 672 R->addRange(range); 673 C.EmitReport(R); 674 } 675} 676 677ProgramStateRef MallocChecker::ReallocMem(CheckerContext &C, 678 const CallExpr *CE, 679 bool FreesOnFail) const { 680 ProgramStateRef state = C.getState(); 681 const Expr *arg0Expr = CE->getArg(0); 682 const LocationContext *LCtx = C.getLocationContext(); 683 SVal Arg0Val = state->getSVal(arg0Expr, LCtx); 684 if (!isa<DefinedOrUnknownSVal>(Arg0Val)) 685 return 0; 686 DefinedOrUnknownSVal arg0Val = cast<DefinedOrUnknownSVal>(Arg0Val); 687 688 SValBuilder &svalBuilder = C.getSValBuilder(); 689 690 DefinedOrUnknownSVal PtrEQ = 691 svalBuilder.evalEQ(state, arg0Val, svalBuilder.makeNull()); 692 693 // Get the size argument. If there is no size arg then give up. 694 const Expr *Arg1 = CE->getArg(1); 695 if (!Arg1) 696 return 0; 697 698 // Get the value of the size argument. 699 SVal Arg1ValG = state->getSVal(Arg1, LCtx); 700 if (!isa<DefinedOrUnknownSVal>(Arg1ValG)) 701 return 0; 702 DefinedOrUnknownSVal Arg1Val = cast<DefinedOrUnknownSVal>(Arg1ValG); 703 704 // Compare the size argument to 0. 705 DefinedOrUnknownSVal SizeZero = 706 svalBuilder.evalEQ(state, Arg1Val, 707 svalBuilder.makeIntValWithPtrWidth(0, false)); 708 709 ProgramStateRef StatePtrIsNull, StatePtrNotNull; 710 llvm::tie(StatePtrIsNull, StatePtrNotNull) = state->assume(PtrEQ); 711 ProgramStateRef StateSizeIsZero, StateSizeNotZero; 712 llvm::tie(StateSizeIsZero, StateSizeNotZero) = state->assume(SizeZero); 713 // We only assume exceptional states if they are definitely true; if the 714 // state is under-constrained, assume regular realloc behavior. 715 bool PrtIsNull = StatePtrIsNull && !StatePtrNotNull; 716 bool SizeIsZero = StateSizeIsZero && !StateSizeNotZero; 717 718 // If the ptr is NULL and the size is not 0, the call is equivalent to 719 // malloc(size). 720 if ( PrtIsNull && !SizeIsZero) { 721 ProgramStateRef stateMalloc = MallocMemAux(C, CE, CE->getArg(1), 722 UndefinedVal(), StatePtrIsNull); 723 return stateMalloc; 724 } 725 726 if (PrtIsNull && SizeIsZero) 727 return 0; 728 729 // Get the from and to pointer symbols as in toPtr = realloc(fromPtr, size). 730 assert(!PrtIsNull); 731 SymbolRef FromPtr = arg0Val.getAsSymbol(); 732 SVal RetVal = state->getSVal(CE, LCtx); 733 SymbolRef ToPtr = RetVal.getAsSymbol(); 734 if (!FromPtr || !ToPtr) 735 return 0; 736 737 // If the size is 0, free the memory. 738 if (SizeIsZero) 739 if (ProgramStateRef stateFree = FreeMemAux(C, CE, StateSizeIsZero,0,false)){ 740 // The semantics of the return value are: 741 // If size was equal to 0, either NULL or a pointer suitable to be passed 742 // to free() is returned. 743 stateFree = stateFree->set<ReallocPairs>(ToPtr, 744 ReallocPair(FromPtr, FreesOnFail)); 745 C.getSymbolManager().addSymbolDependency(ToPtr, FromPtr); 746 return stateFree; 747 } 748 749 // Default behavior. 750 if (ProgramStateRef stateFree = FreeMemAux(C, CE, state, 0, false)) { 751 // FIXME: We should copy the content of the original buffer. 752 ProgramStateRef stateRealloc = MallocMemAux(C, CE, CE->getArg(1), 753 UnknownVal(), stateFree); 754 if (!stateRealloc) 755 return 0; 756 stateRealloc = stateRealloc->set<ReallocPairs>(ToPtr, 757 ReallocPair(FromPtr, FreesOnFail)); 758 C.getSymbolManager().addSymbolDependency(ToPtr, FromPtr); 759 return stateRealloc; 760 } 761 return 0; 762} 763 764ProgramStateRef MallocChecker::CallocMem(CheckerContext &C, const CallExpr *CE){ 765 ProgramStateRef state = C.getState(); 766 SValBuilder &svalBuilder = C.getSValBuilder(); 767 const LocationContext *LCtx = C.getLocationContext(); 768 SVal count = state->getSVal(CE->getArg(0), LCtx); 769 SVal elementSize = state->getSVal(CE->getArg(1), LCtx); 770 SVal TotalSize = svalBuilder.evalBinOp(state, BO_Mul, count, elementSize, 771 svalBuilder.getContext().getSizeType()); 772 SVal zeroVal = svalBuilder.makeZeroVal(svalBuilder.getContext().CharTy); 773 774 return MallocMemAux(C, CE, TotalSize, zeroVal, state); 775} 776 777const Stmt * 778MallocChecker::getAllocationSite(const ExplodedNode *N, SymbolRef Sym, 779 CheckerContext &C) const { 780 const LocationContext *LeakContext = N->getLocationContext(); 781 // Walk the ExplodedGraph backwards and find the first node that referred to 782 // the tracked symbol. 783 const ExplodedNode *AllocNode = N; 784 785 while (N) { 786 if (!N->getState()->get<RegionState>(Sym)) 787 break; 788 // Allocation node, is the last node in the current context in which the 789 // symbol was tracked. 790 if (N->getLocationContext() == LeakContext) 791 AllocNode = N; 792 N = N->pred_empty() ? NULL : *(N->pred_begin()); 793 } 794 795 ProgramPoint P = AllocNode->getLocation(); 796 if (!isa<StmtPoint>(P)) 797 return 0; 798 799 return cast<StmtPoint>(P).getStmt(); 800} 801 802void MallocChecker::reportLeak(SymbolRef Sym, ExplodedNode *N, 803 CheckerContext &C) const { 804 assert(N); 805 if (!BT_Leak) { 806 BT_Leak.reset(new BugType("Memory leak", "Memory Error")); 807 // Leaks should not be reported if they are post-dominated by a sink: 808 // (1) Sinks are higher importance bugs. 809 // (2) NoReturnFunctionChecker uses sink nodes to represent paths ending 810 // with __noreturn functions such as assert() or exit(). We choose not 811 // to report leaks on such paths. 812 BT_Leak->setSuppressOnSink(true); 813 } 814 815 // Most bug reports are cached at the location where they occurred. 816 // With leaks, we want to unique them by the location where they were 817 // allocated, and only report a single path. 818 PathDiagnosticLocation LocUsedForUniqueing; 819 if (const Stmt *AllocStmt = getAllocationSite(N, Sym, C)) 820 LocUsedForUniqueing = PathDiagnosticLocation::createBegin(AllocStmt, 821 C.getSourceManager(), N->getLocationContext()); 822 823 BugReport *R = new BugReport(*BT_Leak, 824 "Memory is never released; potential memory leak", N, LocUsedForUniqueing); 825 R->addVisitor(new MallocBugVisitor(Sym)); 826 C.EmitReport(R); 827} 828 829void MallocChecker::checkDeadSymbols(SymbolReaper &SymReaper, 830 CheckerContext &C) const 831{ 832 if (!SymReaper.hasDeadSymbols()) 833 return; 834 835 ProgramStateRef state = C.getState(); 836 RegionStateTy RS = state->get<RegionState>(); 837 RegionStateTy::Factory &F = state->get_context<RegionState>(); 838 839 bool generateReport = false; 840 llvm::SmallVector<SymbolRef, 2> Errors; 841 for (RegionStateTy::iterator I = RS.begin(), E = RS.end(); I != E; ++I) { 842 if (SymReaper.isDead(I->first)) { 843 if (I->second.isAllocated()) { 844 generateReport = true; 845 Errors.push_back(I->first); 846 } 847 // Remove the dead symbol from the map. 848 RS = F.remove(RS, I->first); 849 850 } 851 } 852 853 // Cleanup the Realloc Pairs Map. 854 ReallocMap RP = state->get<ReallocPairs>(); 855 for (ReallocMap::iterator I = RP.begin(), E = RP.end(); I != E; ++I) { 856 if (SymReaper.isDead(I->first) || 857 SymReaper.isDead(I->second.ReallocatedSym)) { 858 state = state->remove<ReallocPairs>(I->first); 859 } 860 } 861 862 // Generate leak node. 863 static SimpleProgramPointTag Tag("MallocChecker : DeadSymbolsLeak"); 864 ExplodedNode *N = C.addTransition(C.getState(), C.getPredecessor(), &Tag); 865 866 if (generateReport) { 867 for (llvm::SmallVector<SymbolRef, 2>::iterator 868 I = Errors.begin(), E = Errors.end(); I != E; ++I) { 869 reportLeak(*I, N, C); 870 } 871 } 872 C.addTransition(state->set<RegionState>(RS), N); 873} 874 875void MallocChecker::checkEndPath(CheckerContext &C) const { 876 ProgramStateRef state = C.getState(); 877 RegionStateTy M = state->get<RegionState>(); 878 879 // If inside inlined call, skip it. 880 if (C.getLocationContext()->getParent() != 0) 881 return; 882 883 for (RegionStateTy::iterator I = M.begin(), E = M.end(); I != E; ++I) { 884 RefState RS = I->second; 885 if (RS.isAllocated()) { 886 ExplodedNode *N = C.addTransition(state); 887 if (N) 888 reportLeak(I->first, N, C); 889 } 890 } 891} 892 893bool MallocChecker::checkEscape(SymbolRef Sym, const Stmt *S, 894 CheckerContext &C) const { 895 ProgramStateRef state = C.getState(); 896 const RefState *RS = state->get<RegionState>(Sym); 897 if (!RS) 898 return false; 899 900 if (RS->isAllocated()) { 901 state = state->set<RegionState>(Sym, RefState::getEscaped(S)); 902 C.addTransition(state); 903 return true; 904 } 905 return false; 906} 907 908void MallocChecker::checkPreStmt(const CallExpr *CE, CheckerContext &C) const { 909 if (isMemFunction(C.getCalleeDecl(CE), C.getASTContext())) 910 return; 911 912 // Check use after free, when a freed pointer is passed to a call. 913 ProgramStateRef State = C.getState(); 914 for (CallExpr::const_arg_iterator I = CE->arg_begin(), 915 E = CE->arg_end(); I != E; ++I) { 916 const Expr *A = *I; 917 if (A->getType().getTypePtr()->isAnyPointerType()) { 918 SymbolRef Sym = State->getSVal(A, C.getLocationContext()).getAsSymbol(); 919 if (!Sym) 920 continue; 921 if (checkUseAfterFree(Sym, C, A)) 922 return; 923 } 924 } 925} 926 927void MallocChecker::checkPreStmt(const ReturnStmt *S, CheckerContext &C) const { 928 const Expr *E = S->getRetValue(); 929 if (!E) 930 return; 931 932 // Check if we are returning a symbol. 933 SVal RetVal = C.getState()->getSVal(E, C.getLocationContext()); 934 SymbolRef Sym = RetVal.getAsSymbol(); 935 if (!Sym) 936 // If we are returning a field of the allocated struct or an array element, 937 // the callee could still free the memory. 938 // TODO: This logic should be a part of generic symbol escape callback. 939 if (const MemRegion *MR = RetVal.getAsRegion()) 940 if (isa<FieldRegion>(MR) || isa<ElementRegion>(MR)) 941 if (const SymbolicRegion *BMR = 942 dyn_cast<SymbolicRegion>(MR->getBaseRegion())) 943 Sym = BMR->getSymbol(); 944 if (!Sym) 945 return; 946 947 // Check if we are returning freed memory. 948 if (checkUseAfterFree(Sym, C, E)) 949 return; 950 951 // If this function body is not inlined, check if the symbol is escaping. 952 if (C.getLocationContext()->getParent() == 0) 953 checkEscape(Sym, E, C); 954} 955 956bool MallocChecker::checkUseAfterFree(SymbolRef Sym, CheckerContext &C, 957 const Stmt *S) const { 958 assert(Sym); 959 const RefState *RS = C.getState()->get<RegionState>(Sym); 960 if (RS && RS->isReleased()) { 961 if (ExplodedNode *N = C.generateSink()) { 962 if (!BT_UseFree) 963 BT_UseFree.reset(new BugType("Use-after-free", "Memory Error")); 964 965 BugReport *R = new BugReport(*BT_UseFree, 966 "Use of memory after it is freed",N); 967 if (S) 968 R->addRange(S->getSourceRange()); 969 R->addVisitor(new MallocBugVisitor(Sym)); 970 C.EmitReport(R); 971 return true; 972 } 973 } 974 return false; 975} 976 977// Check if the location is a freed symbolic region. 978void MallocChecker::checkLocation(SVal l, bool isLoad, const Stmt *S, 979 CheckerContext &C) const { 980 SymbolRef Sym = l.getLocSymbolInBase(); 981 if (Sym) 982 checkUseAfterFree(Sym, C); 983} 984 985//===----------------------------------------------------------------------===// 986// Check various ways a symbol can be invalidated. 987// TODO: This logic (the next 3 functions) is copied/similar to the 988// RetainRelease checker. We might want to factor this out. 989//===----------------------------------------------------------------------===// 990 991// Stop tracking symbols when a value escapes as a result of checkBind. 992// A value escapes in three possible cases: 993// (1) we are binding to something that is not a memory region. 994// (2) we are binding to a memregion that does not have stack storage 995// (3) we are binding to a memregion with stack storage that the store 996// does not understand. 997void MallocChecker::checkBind(SVal loc, SVal val, const Stmt *S, 998 CheckerContext &C) const { 999 // Are we storing to something that causes the value to "escape"? 1000 bool escapes = true; 1001 ProgramStateRef state = C.getState(); 1002 1003 if (loc::MemRegionVal *regionLoc = dyn_cast<loc::MemRegionVal>(&loc)) { 1004 escapes = !regionLoc->getRegion()->hasStackStorage(); 1005 1006 if (!escapes) { 1007 // To test (3), generate a new state with the binding added. If it is 1008 // the same state, then it escapes (since the store cannot represent 1009 // the binding). 1010 escapes = (state == (state->bindLoc(*regionLoc, val))); 1011 } 1012 if (!escapes) { 1013 // Case 4: We do not currently model what happens when a symbol is 1014 // assigned to a struct field, so be conservative here and let the symbol 1015 // go. TODO: This could definitely be improved upon. 1016 escapes = !isa<VarRegion>(regionLoc->getRegion()); 1017 } 1018 } 1019 1020 // If our store can represent the binding and we aren't storing to something 1021 // that doesn't have local storage then just return and have the simulation 1022 // state continue as is. 1023 if (!escapes) 1024 return; 1025 1026 // Otherwise, find all symbols referenced by 'val' that we are tracking 1027 // and stop tracking them. 1028 state = state->scanReachableSymbols<StopTrackingCallback>(val).getState(); 1029 C.addTransition(state); 1030} 1031 1032// If a symbolic region is assumed to NULL (or another constant), stop tracking 1033// it - assuming that allocation failed on this path. 1034ProgramStateRef MallocChecker::evalAssume(ProgramStateRef state, 1035 SVal Cond, 1036 bool Assumption) const { 1037 RegionStateTy RS = state->get<RegionState>(); 1038 for (RegionStateTy::iterator I = RS.begin(), E = RS.end(); I != E; ++I) { 1039 // If the symbol is assumed to NULL or another constant, this will 1040 // return an APSInt*. 1041 if (state->getSymVal(I.getKey())) 1042 state = state->remove<RegionState>(I.getKey()); 1043 } 1044 1045 // Realloc returns 0 when reallocation fails, which means that we should 1046 // restore the state of the pointer being reallocated. 1047 ReallocMap RP = state->get<ReallocPairs>(); 1048 for (ReallocMap::iterator I = RP.begin(), E = RP.end(); I != E; ++I) { 1049 // If the symbol is assumed to NULL or another constant, this will 1050 // return an APSInt*. 1051 if (state->getSymVal(I.getKey())) { 1052 SymbolRef ReallocSym = I.getData().ReallocatedSym; 1053 const RefState *RS = state->get<RegionState>(ReallocSym); 1054 if (RS) { 1055 if (RS->isReleased() && ! I.getData().IsFreeOnFailure) 1056 state = state->set<RegionState>(ReallocSym, 1057 RefState::getAllocateUnchecked(RS->getStmt())); 1058 } 1059 state = state->remove<ReallocPairs>(I.getKey()); 1060 } 1061 } 1062 1063 return state; 1064} 1065 1066// Check if the function is known to us. So, for example, we could 1067// conservatively assume it can free/reallocate it's pointer arguments. 1068// (We assume that the pointers cannot escape through calls to system 1069// functions not handled by this checker.) 1070bool MallocChecker::doesNotFreeMemory(const CallOrObjCMessage *Call, 1071 ProgramStateRef State) const { 1072 if (!Call) 1073 return false; 1074 1075 // For now, assume that any C++ call can free memory. 1076 // TODO: If we want to be more optimistic here, we'll need to make sure that 1077 // regions escape to C++ containers. They seem to do that even now, but for 1078 // mysterious reasons. 1079 if (Call->isCXXCall()) 1080 return false; 1081 1082 const Decl *D = Call->getDecl(); 1083 if (!D) 1084 return false; 1085 1086 ASTContext &ASTC = State->getStateManager().getContext(); 1087 1088 // If it's one of the allocation functions we can reason about, we model 1089 // it's behavior explicitly. 1090 if (isa<FunctionDecl>(D) && isMemFunction(cast<FunctionDecl>(D), ASTC)) { 1091 return true; 1092 } 1093 1094 // If it's not a system call, assume it frees memory. 1095 SourceManager &SM = ASTC.getSourceManager(); 1096 if (!SM.isInSystemHeader(D->getLocation())) 1097 return false; 1098 1099 // Process C/ObjC functions. 1100 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) { 1101 // White list the system functions whose arguments escape. 1102 const IdentifierInfo *II = FD->getIdentifier(); 1103 if (!II) 1104 return true; 1105 StringRef FName = II->getName(); 1106 1107 // White list thread local storage. 1108 if (FName.equals("pthread_setspecific")) 1109 return false; 1110 1111 // White list the 'XXXNoCopy' ObjC functions. 1112 if (FName.endswith("NoCopy")) { 1113 // Look for the deallocator argument. We know that the memory ownership 1114 // is not transfered only if the deallocator argument is 1115 // 'kCFAllocatorNull'. 1116 for (unsigned i = 1; i < Call->getNumArgs(); ++i) { 1117 const Expr *ArgE = Call->getArg(i)->IgnoreParenCasts(); 1118 if (const DeclRefExpr *DE = dyn_cast<DeclRefExpr>(ArgE)) { 1119 StringRef DeallocatorName = DE->getFoundDecl()->getName(); 1120 if (DeallocatorName == "kCFAllocatorNull") 1121 return true; 1122 } 1123 } 1124 return false; 1125 } 1126 1127 // PR12101 1128 // Many CoreFoundation and CoreGraphics might allow a tracked object 1129 // to escape. 1130 if (Call->isCFCGAllowingEscape(FName)) 1131 return false; 1132 1133 // Associating streams with malloced buffers. The pointer can escape if 1134 // 'closefn' is specified (and if that function does free memory). 1135 // Currently, we do not inspect the 'closefn' function (PR12101). 1136 if (FName == "funopen") 1137 if (Call->getNumArgs() >= 4 && !Call->getArgSVal(4).isConstant(0)) 1138 return false; 1139 1140 // Do not warn on pointers passed to 'setbuf' when used with std streams, 1141 // these leaks might be intentional when setting the buffer for stdio. 1142 // http://stackoverflow.com/questions/2671151/who-frees-setvbuf-buffer 1143 if (FName == "setbuf" || FName =="setbuffer" || 1144 FName == "setlinebuf" || FName == "setvbuf") { 1145 if (Call->getNumArgs() >= 1) 1146 if (const DeclRefExpr *Arg = 1147 dyn_cast<DeclRefExpr>(Call->getArg(0)->IgnoreParenCasts())) 1148 if (const VarDecl *D = dyn_cast<VarDecl>(Arg->getDecl())) 1149 if (D->getCanonicalDecl()->getName().find("std") 1150 != StringRef::npos) 1151 return false; 1152 } 1153 1154 // A bunch of other functions, which take ownership of a pointer (See retain 1155 // release checker). Not all the parameters here are invalidated, but the 1156 // Malloc checker cannot differentiate between them. The right way of doing 1157 // this would be to implement a pointer escapes callback. 1158 if (FName == "CVPixelBufferCreateWithBytes" || 1159 FName == "CGBitmapContextCreateWithData" || 1160 FName == "CVPixelBufferCreateWithPlanarBytes") { 1161 return false; 1162 } 1163 1164 // Otherwise, assume that the function does not free memory. 1165 // Most system calls, do not free the memory. 1166 return true; 1167 1168 // Process ObjC functions. 1169 } else if (const ObjCMethodDecl * ObjCD = dyn_cast<ObjCMethodDecl>(D)) { 1170 Selector S = ObjCD->getSelector(); 1171 1172 // White list the ObjC functions which do free memory. 1173 // - Anything containing 'freeWhenDone' param set to 1. 1174 // Ex: dataWithBytesNoCopy:length:freeWhenDone. 1175 for (unsigned i = 1; i < S.getNumArgs(); ++i) { 1176 if (S.getNameForSlot(i).equals("freeWhenDone")) { 1177 if (Call->getArgSVal(i).isConstant(1)) 1178 return false; 1179 else 1180 return true; 1181 } 1182 } 1183 1184 // If the first selector ends with NoCopy, assume that the ownership is 1185 // transfered as well. 1186 // Ex: [NSData dataWithBytesNoCopy:bytes length:10]; 1187 if (S.getNameForSlot(0).endswith("NoCopy")) { 1188 return false; 1189 } 1190 1191 // Otherwise, assume that the function does not free memory. 1192 // Most system calls, do not free the memory. 1193 return true; 1194 } 1195 1196 // Otherwise, assume that the function can free memory. 1197 return false; 1198 1199} 1200 1201// If the symbol we are tracking is invalidated, but not explicitly (ex: the &p 1202// escapes, when we are tracking p), do not track the symbol as we cannot reason 1203// about it anymore. 1204ProgramStateRef 1205MallocChecker::checkRegionChanges(ProgramStateRef State, 1206 const StoreManager::InvalidatedSymbols *invalidated, 1207 ArrayRef<const MemRegion *> ExplicitRegions, 1208 ArrayRef<const MemRegion *> Regions, 1209 const CallOrObjCMessage *Call) const { 1210 if (!invalidated || invalidated->empty()) 1211 return State; 1212 llvm::SmallPtrSet<SymbolRef, 8> WhitelistedSymbols; 1213 1214 // If it's a call which might free or reallocate memory, we assume that all 1215 // regions (explicit and implicit) escaped. 1216 1217 // Otherwise, whitelist explicit pointers; we still can track them. 1218 if (!Call || doesNotFreeMemory(Call, State)) { 1219 for (ArrayRef<const MemRegion *>::iterator I = ExplicitRegions.begin(), 1220 E = ExplicitRegions.end(); I != E; ++I) { 1221 if (const SymbolicRegion *R = (*I)->StripCasts()->getAs<SymbolicRegion>()) 1222 WhitelistedSymbols.insert(R->getSymbol()); 1223 } 1224 } 1225 1226 for (StoreManager::InvalidatedSymbols::const_iterator I=invalidated->begin(), 1227 E = invalidated->end(); I!=E; ++I) { 1228 SymbolRef sym = *I; 1229 if (WhitelistedSymbols.count(sym)) 1230 continue; 1231 // The symbol escaped. 1232 if (const RefState *RS = State->get<RegionState>(sym)) 1233 State = State->set<RegionState>(sym, RefState::getEscaped(RS->getStmt())); 1234 } 1235 return State; 1236} 1237 1238PathDiagnosticPiece * 1239MallocChecker::MallocBugVisitor::VisitNode(const ExplodedNode *N, 1240 const ExplodedNode *PrevN, 1241 BugReporterContext &BRC, 1242 BugReport &BR) { 1243 const RefState *RS = N->getState()->get<RegionState>(Sym); 1244 const RefState *RSPrev = PrevN->getState()->get<RegionState>(Sym); 1245 if (!RS && !RSPrev) 1246 return 0; 1247 1248 const Stmt *S = 0; 1249 const char *Msg = 0; 1250 1251 // Retrieve the associated statement. 1252 ProgramPoint ProgLoc = N->getLocation(); 1253 if (isa<StmtPoint>(ProgLoc)) 1254 S = cast<StmtPoint>(ProgLoc).getStmt(); 1255 // If an assumption was made on a branch, it should be caught 1256 // here by looking at the state transition. 1257 if (isa<BlockEdge>(ProgLoc)) { 1258 const CFGBlock *srcBlk = cast<BlockEdge>(ProgLoc).getSrc(); 1259 S = srcBlk->getTerminator(); 1260 } 1261 if (!S) 1262 return 0; 1263 1264 // Find out if this is an interesting point and what is the kind. 1265 if (Mode == Normal) { 1266 if (isAllocated(RS, RSPrev, S)) 1267 Msg = "Memory is allocated"; 1268 else if (isReleased(RS, RSPrev, S)) 1269 Msg = "Memory is released"; 1270 else if (isReallocFailedCheck(RS, RSPrev, S)) { 1271 Mode = ReallocationFailed; 1272 Msg = "Reallocation failed"; 1273 } 1274 1275 // We are in a special mode if a reallocation failed later in the path. 1276 } else if (Mode == ReallocationFailed) { 1277 // Generate a special diagnostic for the first realloc we find. 1278 if (!isAllocated(RS, RSPrev, S) && !isReleased(RS, RSPrev, S)) 1279 return 0; 1280 1281 // Check that the name of the function is realloc. 1282 const CallExpr *CE = dyn_cast<CallExpr>(S); 1283 if (!CE) 1284 return 0; 1285 const FunctionDecl *funDecl = CE->getDirectCallee(); 1286 if (!funDecl) 1287 return 0; 1288 StringRef FunName = funDecl->getName(); 1289 if (!(FunName.equals("realloc") || FunName.equals("reallocf"))) 1290 return 0; 1291 Msg = "Attempt to reallocate memory"; 1292 Mode = Normal; 1293 } 1294 1295 if (!Msg) 1296 return 0; 1297 1298 // Generate the extra diagnostic. 1299 PathDiagnosticLocation Pos(S, BRC.getSourceManager(), 1300 N->getLocationContext()); 1301 return new PathDiagnosticEventPiece(Pos, Msg); 1302} 1303 1304 1305#define REGISTER_CHECKER(name) \ 1306void ento::register##name(CheckerManager &mgr) {\ 1307 registerCStringCheckerBasic(mgr); \ 1308 mgr.registerChecker<MallocChecker>()->Filter.C##name = true;\ 1309} 1310 1311REGISTER_CHECKER(MallocPessimistic) 1312REGISTER_CHECKER(MallocOptimistic) 1313