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