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