1 //=== MallocChecker.cpp - A malloc/free checker -------------------*- C++ -*--// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This file defines a variety of memory management related checkers, such as 10 // leak, double free, and use-after-free. 11 // 12 // The following checkers are defined here: 13 // 14 // * MallocChecker 15 // Despite its name, it models all sorts of memory allocations and 16 // de- or reallocation, including but not limited to malloc, free, 17 // relloc, new, delete. It also reports on a variety of memory misuse 18 // errors. 19 // Many other checkers interact very closely with this checker, in fact, 20 // most are merely options to this one. Other checkers may register 21 // MallocChecker, but do not enable MallocChecker's reports (more details 22 // to follow around its field, ChecksEnabled). 23 // It also has a boolean "Optimistic" checker option, which if set to true 24 // will cause the checker to model user defined memory management related 25 // functions annotated via the attribute ownership_takes, ownership_holds 26 // and ownership_returns. 27 // 28 // * NewDeleteChecker 29 // Enables the modeling of new, new[], delete, delete[] in MallocChecker, 30 // and checks for related double-free and use-after-free errors. 31 // 32 // * NewDeleteLeaksChecker 33 // Checks for leaks related to new, new[], delete, delete[]. 34 // Depends on NewDeleteChecker. 35 // 36 // * MismatchedDeallocatorChecker 37 // Enables checking whether memory is deallocated with the correspending 38 // allocation function in MallocChecker, such as malloc() allocated 39 // regions are only freed by free(), new by delete, new[] by delete[]. 40 // 41 // InnerPointerChecker interacts very closely with MallocChecker, but unlike 42 // the above checkers, it has it's own file, hence the many InnerPointerChecker 43 // related headers and non-static functions. 44 // 45 //===----------------------------------------------------------------------===// 46 47 #include "AllocationState.h" 48 #include "InterCheckerAPI.h" 49 #include "clang/AST/Attr.h" 50 #include "clang/AST/DeclCXX.h" 51 #include "clang/AST/DeclTemplate.h" 52 #include "clang/AST/Expr.h" 53 #include "clang/AST/ExprCXX.h" 54 #include "clang/AST/ParentMap.h" 55 #include "clang/ASTMatchers/ASTMatchFinder.h" 56 #include "clang/ASTMatchers/ASTMatchers.h" 57 #include "clang/Analysis/ProgramPoint.h" 58 #include "clang/Basic/LLVM.h" 59 #include "clang/Basic/SourceManager.h" 60 #include "clang/Basic/TargetInfo.h" 61 #include "clang/Lex/Lexer.h" 62 #include "clang/StaticAnalyzer/Checkers/BuiltinCheckerRegistration.h" 63 #include "clang/StaticAnalyzer/Core/BugReporter/BugType.h" 64 #include "clang/StaticAnalyzer/Core/BugReporter/CommonBugCategories.h" 65 #include "clang/StaticAnalyzer/Core/Checker.h" 66 #include "clang/StaticAnalyzer/Core/CheckerManager.h" 67 #include "clang/StaticAnalyzer/Core/PathSensitive/CallDescription.h" 68 #include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h" 69 #include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h" 70 #include "clang/StaticAnalyzer/Core/PathSensitive/CheckerHelpers.h" 71 #include "clang/StaticAnalyzer/Core/PathSensitive/DynamicExtent.h" 72 #include "clang/StaticAnalyzer/Core/PathSensitive/ExplodedGraph.h" 73 #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h" 74 #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramStateTrait.h" 75 #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState_Fwd.h" 76 #include "clang/StaticAnalyzer/Core/PathSensitive/SVals.h" 77 #include "clang/StaticAnalyzer/Core/PathSensitive/StoreRef.h" 78 #include "clang/StaticAnalyzer/Core/PathSensitive/SymbolManager.h" 79 #include "llvm/ADT/STLExtras.h" 80 #include "llvm/ADT/SetOperations.h" 81 #include "llvm/ADT/SmallString.h" 82 #include "llvm/ADT/StringExtras.h" 83 #include "llvm/Support/Casting.h" 84 #include "llvm/Support/Compiler.h" 85 #include "llvm/Support/ErrorHandling.h" 86 #include "llvm/Support/raw_ostream.h" 87 #include <climits> 88 #include <functional> 89 #include <optional> 90 #include <utility> 91 92 using namespace clang; 93 using namespace ento; 94 using namespace std::placeholders; 95 96 //===----------------------------------------------------------------------===// 97 // The types of allocation we're modeling. This is used to check whether a 98 // dynamically allocated object is deallocated with the correct function, like 99 // not using operator delete on an object created by malloc(), or alloca regions 100 // aren't ever deallocated manually. 101 //===----------------------------------------------------------------------===// 102 103 namespace { 104 105 // Used to check correspondence between allocators and deallocators. 106 enum AllocationFamily { 107 AF_None, 108 AF_Malloc, 109 AF_CXXNew, 110 AF_CXXNewArray, 111 AF_IfNameIndex, 112 AF_Alloca, 113 AF_InnerBuffer 114 }; 115 116 } // end of anonymous namespace 117 118 /// Print names of allocators and deallocators. 119 /// 120 /// \returns true on success. 121 static bool printMemFnName(raw_ostream &os, CheckerContext &C, const Expr *E); 122 123 /// Print expected name of an allocator based on the deallocator's family 124 /// derived from the DeallocExpr. 125 static void printExpectedAllocName(raw_ostream &os, AllocationFamily Family); 126 127 /// Print expected name of a deallocator based on the allocator's 128 /// family. 129 static void printExpectedDeallocName(raw_ostream &os, AllocationFamily Family); 130 131 //===----------------------------------------------------------------------===// 132 // The state of a symbol, in terms of memory management. 133 //===----------------------------------------------------------------------===// 134 135 namespace { 136 137 class RefState { 138 enum Kind { 139 // Reference to allocated memory. 140 Allocated, 141 // Reference to zero-allocated memory. 142 AllocatedOfSizeZero, 143 // Reference to released/freed memory. 144 Released, 145 // The responsibility for freeing resources has transferred from 146 // this reference. A relinquished symbol should not be freed. 147 Relinquished, 148 // We are no longer guaranteed to have observed all manipulations 149 // of this pointer/memory. For example, it could have been 150 // passed as a parameter to an opaque function. 151 Escaped 152 }; 153 154 const Stmt *S; 155 156 Kind K; 157 AllocationFamily Family; 158 159 RefState(Kind k, const Stmt *s, AllocationFamily family) 160 : S(s), K(k), Family(family) { 161 assert(family != AF_None); 162 } 163 164 public: 165 bool isAllocated() const { return K == Allocated; } 166 bool isAllocatedOfSizeZero() const { return K == AllocatedOfSizeZero; } 167 bool isReleased() const { return K == Released; } 168 bool isRelinquished() const { return K == Relinquished; } 169 bool isEscaped() const { return K == Escaped; } 170 AllocationFamily getAllocationFamily() const { return Family; } 171 const Stmt *getStmt() const { return S; } 172 173 bool operator==(const RefState &X) const { 174 return K == X.K && S == X.S && Family == X.Family; 175 } 176 177 static RefState getAllocated(AllocationFamily family, const Stmt *s) { 178 return RefState(Allocated, s, family); 179 } 180 static RefState getAllocatedOfSizeZero(const RefState *RS) { 181 return RefState(AllocatedOfSizeZero, RS->getStmt(), 182 RS->getAllocationFamily()); 183 } 184 static RefState getReleased(AllocationFamily family, const Stmt *s) { 185 return RefState(Released, s, family); 186 } 187 static RefState getRelinquished(AllocationFamily family, const Stmt *s) { 188 return RefState(Relinquished, s, family); 189 } 190 static RefState getEscaped(const RefState *RS) { 191 return RefState(Escaped, RS->getStmt(), RS->getAllocationFamily()); 192 } 193 194 void Profile(llvm::FoldingSetNodeID &ID) const { 195 ID.AddInteger(K); 196 ID.AddPointer(S); 197 ID.AddInteger(Family); 198 } 199 200 LLVM_DUMP_METHOD void dump(raw_ostream &OS) const { 201 switch (K) { 202 #define CASE(ID) case ID: OS << #ID; break; 203 CASE(Allocated) 204 CASE(AllocatedOfSizeZero) 205 CASE(Released) 206 CASE(Relinquished) 207 CASE(Escaped) 208 } 209 } 210 211 LLVM_DUMP_METHOD void dump() const { dump(llvm::errs()); } 212 }; 213 214 } // end of anonymous namespace 215 216 REGISTER_MAP_WITH_PROGRAMSTATE(RegionState, SymbolRef, RefState) 217 218 /// Check if the memory associated with this symbol was released. 219 static bool isReleased(SymbolRef Sym, CheckerContext &C); 220 221 /// Update the RefState to reflect the new memory allocation. 222 /// The optional \p RetVal parameter specifies the newly allocated pointer 223 /// value; if unspecified, the value of expression \p E is used. 224 static ProgramStateRef 225 MallocUpdateRefState(CheckerContext &C, const Expr *E, ProgramStateRef State, 226 AllocationFamily Family, 227 Optional<SVal> RetVal = std::nullopt); 228 229 //===----------------------------------------------------------------------===// 230 // The modeling of memory reallocation. 231 // 232 // The terminology 'toPtr' and 'fromPtr' will be used: 233 // toPtr = realloc(fromPtr, 20); 234 //===----------------------------------------------------------------------===// 235 236 REGISTER_SET_WITH_PROGRAMSTATE(ReallocSizeZeroSymbols, SymbolRef) 237 238 namespace { 239 240 /// The state of 'fromPtr' after reallocation is known to have failed. 241 enum OwnershipAfterReallocKind { 242 // The symbol needs to be freed (e.g.: realloc) 243 OAR_ToBeFreedAfterFailure, 244 // The symbol has been freed (e.g.: reallocf) 245 OAR_FreeOnFailure, 246 // The symbol doesn't have to freed (e.g.: we aren't sure if, how and where 247 // 'fromPtr' was allocated: 248 // void Haha(int *ptr) { 249 // ptr = realloc(ptr, 67); 250 // // ... 251 // } 252 // ). 253 OAR_DoNotTrackAfterFailure 254 }; 255 256 /// Stores information about the 'fromPtr' symbol after reallocation. 257 /// 258 /// This is important because realloc may fail, and that needs special modeling. 259 /// Whether reallocation failed or not will not be known until later, so we'll 260 /// store whether upon failure 'fromPtr' will be freed, or needs to be freed 261 /// later, etc. 262 struct ReallocPair { 263 264 // The 'fromPtr'. 265 SymbolRef ReallocatedSym; 266 OwnershipAfterReallocKind Kind; 267 268 ReallocPair(SymbolRef S, OwnershipAfterReallocKind K) 269 : ReallocatedSym(S), Kind(K) {} 270 void Profile(llvm::FoldingSetNodeID &ID) const { 271 ID.AddInteger(Kind); 272 ID.AddPointer(ReallocatedSym); 273 } 274 bool operator==(const ReallocPair &X) const { 275 return ReallocatedSym == X.ReallocatedSym && 276 Kind == X.Kind; 277 } 278 }; 279 280 } // end of anonymous namespace 281 282 REGISTER_MAP_WITH_PROGRAMSTATE(ReallocPairs, SymbolRef, ReallocPair) 283 284 /// Tells if the callee is one of the builtin new/delete operators, including 285 /// placement operators and other standard overloads. 286 static bool isStandardNewDelete(const FunctionDecl *FD); 287 static bool isStandardNewDelete(const CallEvent &Call) { 288 if (!Call.getDecl() || !isa<FunctionDecl>(Call.getDecl())) 289 return false; 290 return isStandardNewDelete(cast<FunctionDecl>(Call.getDecl())); 291 } 292 293 //===----------------------------------------------------------------------===// 294 // Definition of the MallocChecker class. 295 //===----------------------------------------------------------------------===// 296 297 namespace { 298 299 class MallocChecker 300 : public Checker<check::DeadSymbols, check::PointerEscape, 301 check::ConstPointerEscape, check::PreStmt<ReturnStmt>, 302 check::EndFunction, check::PreCall, check::PostCall, 303 check::NewAllocator, check::PostStmt<BlockExpr>, 304 check::PostObjCMessage, check::Location, eval::Assume> { 305 public: 306 /// In pessimistic mode, the checker assumes that it does not know which 307 /// functions might free the memory. 308 /// In optimistic mode, the checker assumes that all user-defined functions 309 /// which might free a pointer are annotated. 310 bool ShouldIncludeOwnershipAnnotatedFunctions = false; 311 312 bool ShouldRegisterNoOwnershipChangeVisitor = false; 313 314 /// Many checkers are essentially built into this one, so enabling them will 315 /// make MallocChecker perform additional modeling and reporting. 316 enum CheckKind { 317 /// When a subchecker is enabled but MallocChecker isn't, model memory 318 /// management but do not emit warnings emitted with MallocChecker only 319 /// enabled. 320 CK_MallocChecker, 321 CK_NewDeleteChecker, 322 CK_NewDeleteLeaksChecker, 323 CK_MismatchedDeallocatorChecker, 324 CK_InnerPointerChecker, 325 CK_NumCheckKinds 326 }; 327 328 using LeakInfo = std::pair<const ExplodedNode *, const MemRegion *>; 329 330 bool ChecksEnabled[CK_NumCheckKinds] = {false}; 331 CheckerNameRef CheckNames[CK_NumCheckKinds]; 332 333 void checkPreCall(const CallEvent &Call, CheckerContext &C) const; 334 void checkPostCall(const CallEvent &Call, CheckerContext &C) const; 335 void checkNewAllocator(const CXXAllocatorCall &Call, CheckerContext &C) const; 336 void checkPostObjCMessage(const ObjCMethodCall &Call, CheckerContext &C) const; 337 void checkPostStmt(const BlockExpr *BE, CheckerContext &C) const; 338 void checkDeadSymbols(SymbolReaper &SymReaper, CheckerContext &C) const; 339 void checkPreStmt(const ReturnStmt *S, CheckerContext &C) const; 340 void checkEndFunction(const ReturnStmt *S, CheckerContext &C) const; 341 ProgramStateRef evalAssume(ProgramStateRef state, SVal Cond, 342 bool Assumption) const; 343 void checkLocation(SVal l, bool isLoad, const Stmt *S, 344 CheckerContext &C) const; 345 346 ProgramStateRef checkPointerEscape(ProgramStateRef State, 347 const InvalidatedSymbols &Escaped, 348 const CallEvent *Call, 349 PointerEscapeKind Kind) const; 350 ProgramStateRef checkConstPointerEscape(ProgramStateRef State, 351 const InvalidatedSymbols &Escaped, 352 const CallEvent *Call, 353 PointerEscapeKind Kind) const; 354 355 void printState(raw_ostream &Out, ProgramStateRef State, 356 const char *NL, const char *Sep) const override; 357 358 private: 359 mutable std::unique_ptr<BugType> BT_DoubleFree[CK_NumCheckKinds]; 360 mutable std::unique_ptr<BugType> BT_DoubleDelete; 361 mutable std::unique_ptr<BugType> BT_Leak[CK_NumCheckKinds]; 362 mutable std::unique_ptr<BugType> BT_UseFree[CK_NumCheckKinds]; 363 mutable std::unique_ptr<BugType> BT_BadFree[CK_NumCheckKinds]; 364 mutable std::unique_ptr<BugType> BT_FreeAlloca[CK_NumCheckKinds]; 365 mutable std::unique_ptr<BugType> BT_MismatchedDealloc; 366 mutable std::unique_ptr<BugType> BT_OffsetFree[CK_NumCheckKinds]; 367 mutable std::unique_ptr<BugType> BT_UseZerroAllocated[CK_NumCheckKinds]; 368 369 #define CHECK_FN(NAME) \ 370 void NAME(const CallEvent &Call, CheckerContext &C) const; 371 372 CHECK_FN(checkFree) 373 CHECK_FN(checkIfNameIndex) 374 CHECK_FN(checkBasicAlloc) 375 CHECK_FN(checkKernelMalloc) 376 CHECK_FN(checkCalloc) 377 CHECK_FN(checkAlloca) 378 CHECK_FN(checkStrdup) 379 CHECK_FN(checkIfFreeNameIndex) 380 CHECK_FN(checkCXXNewOrCXXDelete) 381 CHECK_FN(checkGMalloc0) 382 CHECK_FN(checkGMemdup) 383 CHECK_FN(checkGMallocN) 384 CHECK_FN(checkGMallocN0) 385 CHECK_FN(checkReallocN) 386 CHECK_FN(checkOwnershipAttr) 387 388 void checkRealloc(const CallEvent &Call, CheckerContext &C, 389 bool ShouldFreeOnFail) const; 390 391 using CheckFn = std::function<void(const MallocChecker *, 392 const CallEvent &Call, CheckerContext &C)>; 393 394 const CallDescriptionMap<CheckFn> FreeingMemFnMap{ 395 {{"free", 1}, &MallocChecker::checkFree}, 396 {{"if_freenameindex", 1}, &MallocChecker::checkIfFreeNameIndex}, 397 {{"kfree", 1}, &MallocChecker::checkFree}, 398 {{"g_free", 1}, &MallocChecker::checkFree}, 399 }; 400 401 bool isFreeingCall(const CallEvent &Call) const; 402 static bool isFreeingOwnershipAttrCall(const FunctionDecl *Func); 403 404 friend class NoOwnershipChangeVisitor; 405 406 CallDescriptionMap<CheckFn> AllocatingMemFnMap{ 407 {{"alloca", 1}, &MallocChecker::checkAlloca}, 408 {{"_alloca", 1}, &MallocChecker::checkAlloca}, 409 {{"malloc", 1}, &MallocChecker::checkBasicAlloc}, 410 {{"malloc", 3}, &MallocChecker::checkKernelMalloc}, 411 {{"calloc", 2}, &MallocChecker::checkCalloc}, 412 {{"valloc", 1}, &MallocChecker::checkBasicAlloc}, 413 {{CDF_MaybeBuiltin, "strndup", 2}, &MallocChecker::checkStrdup}, 414 {{CDF_MaybeBuiltin, "strdup", 1}, &MallocChecker::checkStrdup}, 415 {{"_strdup", 1}, &MallocChecker::checkStrdup}, 416 {{"kmalloc", 2}, &MallocChecker::checkKernelMalloc}, 417 {{"if_nameindex", 1}, &MallocChecker::checkIfNameIndex}, 418 {{CDF_MaybeBuiltin, "wcsdup", 1}, &MallocChecker::checkStrdup}, 419 {{CDF_MaybeBuiltin, "_wcsdup", 1}, &MallocChecker::checkStrdup}, 420 {{"g_malloc", 1}, &MallocChecker::checkBasicAlloc}, 421 {{"g_malloc0", 1}, &MallocChecker::checkGMalloc0}, 422 {{"g_try_malloc", 1}, &MallocChecker::checkBasicAlloc}, 423 {{"g_try_malloc0", 1}, &MallocChecker::checkGMalloc0}, 424 {{"g_memdup", 2}, &MallocChecker::checkGMemdup}, 425 {{"g_malloc_n", 2}, &MallocChecker::checkGMallocN}, 426 {{"g_malloc0_n", 2}, &MallocChecker::checkGMallocN0}, 427 {{"g_try_malloc_n", 2}, &MallocChecker::checkGMallocN}, 428 {{"g_try_malloc0_n", 2}, &MallocChecker::checkGMallocN0}, 429 }; 430 431 CallDescriptionMap<CheckFn> ReallocatingMemFnMap{ 432 {{"realloc", 2}, 433 std::bind(&MallocChecker::checkRealloc, _1, _2, _3, false)}, 434 {{"reallocf", 2}, 435 std::bind(&MallocChecker::checkRealloc, _1, _2, _3, true)}, 436 {{"g_realloc", 2}, 437 std::bind(&MallocChecker::checkRealloc, _1, _2, _3, false)}, 438 {{"g_try_realloc", 2}, 439 std::bind(&MallocChecker::checkRealloc, _1, _2, _3, false)}, 440 {{"g_realloc_n", 3}, &MallocChecker::checkReallocN}, 441 {{"g_try_realloc_n", 3}, &MallocChecker::checkReallocN}, 442 }; 443 444 bool isMemCall(const CallEvent &Call) const; 445 446 // TODO: Remove mutable by moving the initializtaion to the registry function. 447 mutable std::optional<uint64_t> KernelZeroFlagVal; 448 449 using KernelZeroSizePtrValueTy = Optional<int>; 450 /// Store the value of macro called `ZERO_SIZE_PTR`. 451 /// The value is initialized at first use, before first use the outer 452 /// Optional is empty, afterwards it contains another Optional that indicates 453 /// if the macro value could be determined, and if yes the value itself. 454 mutable std::optional<KernelZeroSizePtrValueTy> KernelZeroSizePtrValue; 455 456 /// Process C++ operator new()'s allocation, which is the part of C++ 457 /// new-expression that goes before the constructor. 458 [[nodiscard]] ProgramStateRef 459 processNewAllocation(const CXXAllocatorCall &Call, CheckerContext &C, 460 AllocationFamily Family) const; 461 462 /// Perform a zero-allocation check. 463 /// 464 /// \param [in] Call The expression that allocates memory. 465 /// \param [in] IndexOfSizeArg Index of the argument that specifies the size 466 /// of the memory that needs to be allocated. E.g. for malloc, this would be 467 /// 0. 468 /// \param [in] RetVal Specifies the newly allocated pointer value; 469 /// if unspecified, the value of expression \p E is used. 470 [[nodiscard]] static ProgramStateRef 471 ProcessZeroAllocCheck(const CallEvent &Call, const unsigned IndexOfSizeArg, 472 ProgramStateRef State, 473 Optional<SVal> RetVal = std::nullopt); 474 475 /// Model functions with the ownership_returns attribute. 476 /// 477 /// User-defined function may have the ownership_returns attribute, which 478 /// annotates that the function returns with an object that was allocated on 479 /// the heap, and passes the ownertship to the callee. 480 /// 481 /// void __attribute((ownership_returns(malloc, 1))) *my_malloc(size_t); 482 /// 483 /// It has two parameters: 484 /// - first: name of the resource (e.g. 'malloc') 485 /// - (OPTIONAL) second: size of the allocated region 486 /// 487 /// \param [in] Call The expression that allocates memory. 488 /// \param [in] Att The ownership_returns attribute. 489 /// \param [in] State The \c ProgramState right before allocation. 490 /// \returns The ProgramState right after allocation. 491 [[nodiscard]] ProgramStateRef 492 MallocMemReturnsAttr(CheckerContext &C, const CallEvent &Call, 493 const OwnershipAttr *Att, ProgramStateRef State) const; 494 495 /// Models memory allocation. 496 /// 497 /// \param [in] Call The expression that allocates memory. 498 /// \param [in] SizeEx Size of the memory that needs to be allocated. 499 /// \param [in] Init The value the allocated memory needs to be initialized. 500 /// with. For example, \c calloc initializes the allocated memory to 0, 501 /// malloc leaves it undefined. 502 /// \param [in] State The \c ProgramState right before allocation. 503 /// \returns The ProgramState right after allocation. 504 [[nodiscard]] static ProgramStateRef 505 MallocMemAux(CheckerContext &C, const CallEvent &Call, const Expr *SizeEx, 506 SVal Init, ProgramStateRef State, AllocationFamily Family); 507 508 /// Models memory allocation. 509 /// 510 /// \param [in] Call The expression that allocates memory. 511 /// \param [in] Size Size of the memory that needs to be allocated. 512 /// \param [in] Init The value the allocated memory needs to be initialized. 513 /// with. For example, \c calloc initializes the allocated memory to 0, 514 /// malloc leaves it undefined. 515 /// \param [in] State The \c ProgramState right before allocation. 516 /// \returns The ProgramState right after allocation. 517 [[nodiscard]] static ProgramStateRef 518 MallocMemAux(CheckerContext &C, const CallEvent &Call, SVal Size, SVal Init, 519 ProgramStateRef State, AllocationFamily Family); 520 521 // Check if this malloc() for special flags. At present that means M_ZERO or 522 // __GFP_ZERO (in which case, treat it like calloc). 523 [[nodiscard]] llvm::Optional<ProgramStateRef> 524 performKernelMalloc(const CallEvent &Call, CheckerContext &C, 525 const ProgramStateRef &State) const; 526 527 /// Model functions with the ownership_takes and ownership_holds attributes. 528 /// 529 /// User-defined function may have the ownership_takes and/or ownership_holds 530 /// attributes, which annotates that the function frees the memory passed as a 531 /// parameter. 532 /// 533 /// void __attribute((ownership_takes(malloc, 1))) my_free(void *); 534 /// void __attribute((ownership_holds(malloc, 1))) my_hold(void *); 535 /// 536 /// They have two parameters: 537 /// - first: name of the resource (e.g. 'malloc') 538 /// - second: index of the parameter the attribute applies to 539 /// 540 /// \param [in] Call The expression that frees memory. 541 /// \param [in] Att The ownership_takes or ownership_holds attribute. 542 /// \param [in] State The \c ProgramState right before allocation. 543 /// \returns The ProgramState right after deallocation. 544 [[nodiscard]] ProgramStateRef FreeMemAttr(CheckerContext &C, 545 const CallEvent &Call, 546 const OwnershipAttr *Att, 547 ProgramStateRef State) const; 548 549 /// Models memory deallocation. 550 /// 551 /// \param [in] Call The expression that frees memory. 552 /// \param [in] State The \c ProgramState right before allocation. 553 /// \param [in] Num Index of the argument that needs to be freed. This is 554 /// normally 0, but for custom free functions it may be different. 555 /// \param [in] Hold Whether the parameter at \p Index has the ownership_holds 556 /// attribute. 557 /// \param [out] IsKnownToBeAllocated Whether the memory to be freed is known 558 /// to have been allocated, or in other words, the symbol to be freed was 559 /// registered as allocated by this checker. In the following case, \c ptr 560 /// isn't known to be allocated. 561 /// void Haha(int *ptr) { 562 /// ptr = realloc(ptr, 67); 563 /// // ... 564 /// } 565 /// \param [in] ReturnsNullOnFailure Whether the memory deallocation function 566 /// we're modeling returns with Null on failure. 567 /// \returns The ProgramState right after deallocation. 568 [[nodiscard]] ProgramStateRef 569 FreeMemAux(CheckerContext &C, const CallEvent &Call, ProgramStateRef State, 570 unsigned Num, bool Hold, bool &IsKnownToBeAllocated, 571 AllocationFamily Family, bool ReturnsNullOnFailure = false) const; 572 573 /// Models memory deallocation. 574 /// 575 /// \param [in] ArgExpr The variable who's pointee needs to be freed. 576 /// \param [in] Call The expression that frees the memory. 577 /// \param [in] State The \c ProgramState right before allocation. 578 /// normally 0, but for custom free functions it may be different. 579 /// \param [in] Hold Whether the parameter at \p Index has the ownership_holds 580 /// attribute. 581 /// \param [out] IsKnownToBeAllocated Whether the memory to be freed is known 582 /// to have been allocated, or in other words, the symbol to be freed was 583 /// registered as allocated by this checker. In the following case, \c ptr 584 /// isn't known to be allocated. 585 /// void Haha(int *ptr) { 586 /// ptr = realloc(ptr, 67); 587 /// // ... 588 /// } 589 /// \param [in] ReturnsNullOnFailure Whether the memory deallocation function 590 /// we're modeling returns with Null on failure. 591 /// \returns The ProgramState right after deallocation. 592 [[nodiscard]] ProgramStateRef 593 FreeMemAux(CheckerContext &C, const Expr *ArgExpr, const CallEvent &Call, 594 ProgramStateRef State, bool Hold, bool &IsKnownToBeAllocated, 595 AllocationFamily Family, bool ReturnsNullOnFailure = false) const; 596 597 // TODO: Needs some refactoring, as all other deallocation modeling 598 // functions are suffering from out parameters and messy code due to how 599 // realloc is handled. 600 // 601 /// Models memory reallocation. 602 /// 603 /// \param [in] Call The expression that reallocated memory 604 /// \param [in] ShouldFreeOnFail Whether if reallocation fails, the supplied 605 /// memory should be freed. 606 /// \param [in] State The \c ProgramState right before reallocation. 607 /// \param [in] SuffixWithN Whether the reallocation function we're modeling 608 /// has an '_n' suffix, such as g_realloc_n. 609 /// \returns The ProgramState right after reallocation. 610 [[nodiscard]] ProgramStateRef 611 ReallocMemAux(CheckerContext &C, const CallEvent &Call, bool ShouldFreeOnFail, 612 ProgramStateRef State, AllocationFamily Family, 613 bool SuffixWithN = false) const; 614 615 /// Evaluates the buffer size that needs to be allocated. 616 /// 617 /// \param [in] Blocks The amount of blocks that needs to be allocated. 618 /// \param [in] BlockBytes The size of a block. 619 /// \returns The symbolic value of \p Blocks * \p BlockBytes. 620 [[nodiscard]] static SVal evalMulForBufferSize(CheckerContext &C, 621 const Expr *Blocks, 622 const Expr *BlockBytes); 623 624 /// Models zero initialized array allocation. 625 /// 626 /// \param [in] Call The expression that reallocated memory 627 /// \param [in] State The \c ProgramState right before reallocation. 628 /// \returns The ProgramState right after allocation. 629 [[nodiscard]] static ProgramStateRef 630 CallocMem(CheckerContext &C, const CallEvent &Call, ProgramStateRef State); 631 632 /// See if deallocation happens in a suspicious context. If so, escape the 633 /// pointers that otherwise would have been deallocated and return true. 634 bool suppressDeallocationsInSuspiciousContexts(const CallEvent &Call, 635 CheckerContext &C) const; 636 637 /// If in \p S \p Sym is used, check whether \p Sym was already freed. 638 bool checkUseAfterFree(SymbolRef Sym, CheckerContext &C, const Stmt *S) const; 639 640 /// If in \p S \p Sym is used, check whether \p Sym was allocated as a zero 641 /// sized memory region. 642 void checkUseZeroAllocated(SymbolRef Sym, CheckerContext &C, 643 const Stmt *S) const; 644 645 /// If in \p S \p Sym is being freed, check whether \p Sym was already freed. 646 bool checkDoubleDelete(SymbolRef Sym, CheckerContext &C) const; 647 648 /// Check if the function is known to free memory, or if it is 649 /// "interesting" and should be modeled explicitly. 650 /// 651 /// \param [out] EscapingSymbol A function might not free memory in general, 652 /// but could be known to free a particular symbol. In this case, false is 653 /// returned and the single escaping symbol is returned through the out 654 /// parameter. 655 /// 656 /// We assume that pointers do not escape through calls to system functions 657 /// not handled by this checker. 658 bool mayFreeAnyEscapedMemoryOrIsModeledExplicitly(const CallEvent *Call, 659 ProgramStateRef State, 660 SymbolRef &EscapingSymbol) const; 661 662 /// Implementation of the checkPointerEscape callbacks. 663 [[nodiscard]] ProgramStateRef 664 checkPointerEscapeAux(ProgramStateRef State, 665 const InvalidatedSymbols &Escaped, 666 const CallEvent *Call, PointerEscapeKind Kind, 667 bool IsConstPointerEscape) const; 668 669 // Implementation of the checkPreStmt and checkEndFunction callbacks. 670 void checkEscapeOnReturn(const ReturnStmt *S, CheckerContext &C) const; 671 672 ///@{ 673 /// Tells if a given family/call/symbol is tracked by the current checker. 674 /// Sets CheckKind to the kind of the checker responsible for this 675 /// family/call/symbol. 676 Optional<CheckKind> getCheckIfTracked(AllocationFamily Family, 677 bool IsALeakCheck = false) const; 678 679 Optional<CheckKind> getCheckIfTracked(CheckerContext &C, SymbolRef Sym, 680 bool IsALeakCheck = false) const; 681 ///@} 682 static bool SummarizeValue(raw_ostream &os, SVal V); 683 static bool SummarizeRegion(raw_ostream &os, const MemRegion *MR); 684 685 void HandleNonHeapDealloc(CheckerContext &C, SVal ArgVal, SourceRange Range, 686 const Expr *DeallocExpr, 687 AllocationFamily Family) const; 688 689 void HandleFreeAlloca(CheckerContext &C, SVal ArgVal, 690 SourceRange Range) const; 691 692 void HandleMismatchedDealloc(CheckerContext &C, SourceRange Range, 693 const Expr *DeallocExpr, const RefState *RS, 694 SymbolRef Sym, bool OwnershipTransferred) const; 695 696 void HandleOffsetFree(CheckerContext &C, SVal ArgVal, SourceRange Range, 697 const Expr *DeallocExpr, AllocationFamily Family, 698 const Expr *AllocExpr = nullptr) const; 699 700 void HandleUseAfterFree(CheckerContext &C, SourceRange Range, 701 SymbolRef Sym) const; 702 703 void HandleDoubleFree(CheckerContext &C, SourceRange Range, bool Released, 704 SymbolRef Sym, SymbolRef PrevSym) const; 705 706 void HandleDoubleDelete(CheckerContext &C, SymbolRef Sym) const; 707 708 void HandleUseZeroAlloc(CheckerContext &C, SourceRange Range, 709 SymbolRef Sym) const; 710 711 void HandleFunctionPtrFree(CheckerContext &C, SVal ArgVal, SourceRange Range, 712 const Expr *FreeExpr, 713 AllocationFamily Family) const; 714 715 /// Find the location of the allocation for Sym on the path leading to the 716 /// exploded node N. 717 static LeakInfo getAllocationSite(const ExplodedNode *N, SymbolRef Sym, 718 CheckerContext &C); 719 720 void HandleLeak(SymbolRef Sym, ExplodedNode *N, CheckerContext &C) const; 721 722 /// Test if value in ArgVal equals to value in macro `ZERO_SIZE_PTR`. 723 bool isArgZERO_SIZE_PTR(ProgramStateRef State, CheckerContext &C, 724 SVal ArgVal) const; 725 }; 726 } // end anonymous namespace 727 728 //===----------------------------------------------------------------------===// 729 // Definition of NoOwnershipChangeVisitor. 730 //===----------------------------------------------------------------------===// 731 732 namespace { 733 class NoOwnershipChangeVisitor final : public NoStateChangeFuncVisitor { 734 // The symbol whose (lack of) ownership change we are interested in. 735 SymbolRef Sym; 736 const MallocChecker &Checker; 737 using OwnerSet = llvm::SmallPtrSet<const MemRegion *, 8>; 738 739 // Collect which entities point to the allocated memory, and could be 740 // responsible for deallocating it. 741 class OwnershipBindingsHandler : public StoreManager::BindingsHandler { 742 SymbolRef Sym; 743 OwnerSet &Owners; 744 745 public: 746 OwnershipBindingsHandler(SymbolRef Sym, OwnerSet &Owners) 747 : Sym(Sym), Owners(Owners) {} 748 749 bool HandleBinding(StoreManager &SMgr, Store Store, const MemRegion *Region, 750 SVal Val) override { 751 if (Val.getAsSymbol() == Sym) 752 Owners.insert(Region); 753 return true; 754 } 755 756 LLVM_DUMP_METHOD void dump() const { dumpToStream(llvm::errs()); } 757 LLVM_DUMP_METHOD void dumpToStream(llvm::raw_ostream &out) const { 758 out << "Owners: {\n"; 759 for (const MemRegion *Owner : Owners) { 760 out << " "; 761 Owner->dumpToStream(out); 762 out << ",\n"; 763 } 764 out << "}\n"; 765 } 766 }; 767 768 protected: 769 OwnerSet getOwnersAtNode(const ExplodedNode *N) { 770 OwnerSet Ret; 771 772 ProgramStateRef State = N->getState(); 773 OwnershipBindingsHandler Handler{Sym, Ret}; 774 State->getStateManager().getStoreManager().iterBindings(State->getStore(), 775 Handler); 776 return Ret; 777 } 778 779 LLVM_DUMP_METHOD static std::string 780 getFunctionName(const ExplodedNode *CallEnterN) { 781 if (const CallExpr *CE = llvm::dyn_cast_or_null<CallExpr>( 782 CallEnterN->getLocationAs<CallEnter>()->getCallExpr())) 783 if (const FunctionDecl *FD = CE->getDirectCallee()) 784 return FD->getQualifiedNameAsString(); 785 return ""; 786 } 787 788 /// Syntactically checks whether the callee is a deallocating function. Since 789 /// we have no path-sensitive information on this call (we would need a 790 /// CallEvent instead of a CallExpr for that), its possible that a 791 /// deallocation function was called indirectly through a function pointer, 792 /// but we are not able to tell, so this is a best effort analysis. 793 /// See namespace `memory_passed_to_fn_call_free_through_fn_ptr` in 794 /// clang/test/Analysis/NewDeleteLeaks.cpp. 795 bool isFreeingCallAsWritten(const CallExpr &Call) const { 796 if (Checker.FreeingMemFnMap.lookupAsWritten(Call) || 797 Checker.ReallocatingMemFnMap.lookupAsWritten(Call)) 798 return true; 799 800 if (const auto *Func = 801 llvm::dyn_cast_or_null<FunctionDecl>(Call.getCalleeDecl())) 802 return MallocChecker::isFreeingOwnershipAttrCall(Func); 803 804 return false; 805 } 806 807 /// Heuristically guess whether the callee intended to free memory. This is 808 /// done syntactically, because we are trying to argue about alternative 809 /// paths of execution, and as a consequence we don't have path-sensitive 810 /// information. 811 bool doesFnIntendToHandleOwnership(const Decl *Callee, ASTContext &ACtx) { 812 using namespace clang::ast_matchers; 813 const FunctionDecl *FD = dyn_cast<FunctionDecl>(Callee); 814 815 // Given that the stack frame was entered, the body should always be 816 // theoretically obtainable. In case of body farms, the synthesized body 817 // is not attached to declaration, thus triggering the '!FD->hasBody()' 818 // branch. That said, would a synthesized body ever intend to handle 819 // ownership? As of today they don't. And if they did, how would we 820 // put notes inside it, given that it doesn't match any source locations? 821 if (!FD || !FD->hasBody()) 822 return false; 823 824 auto Matches = match(findAll(stmt(anyOf(cxxDeleteExpr().bind("delete"), 825 callExpr().bind("call")))), 826 *FD->getBody(), ACtx); 827 for (BoundNodes Match : Matches) { 828 if (Match.getNodeAs<CXXDeleteExpr>("delete")) 829 return true; 830 831 if (const auto *Call = Match.getNodeAs<CallExpr>("call")) 832 if (isFreeingCallAsWritten(*Call)) 833 return true; 834 } 835 // TODO: Ownership might change with an attempt to store the allocated 836 // memory, not only through deallocation. Check for attempted stores as 837 // well. 838 return false; 839 } 840 841 bool wasModifiedInFunction(const ExplodedNode *CallEnterN, 842 const ExplodedNode *CallExitEndN) override { 843 if (!doesFnIntendToHandleOwnership( 844 CallExitEndN->getFirstPred()->getLocationContext()->getDecl(), 845 CallExitEndN->getState()->getAnalysisManager().getASTContext())) 846 return true; 847 848 if (CallEnterN->getState()->get<RegionState>(Sym) != 849 CallExitEndN->getState()->get<RegionState>(Sym)) 850 return true; 851 852 OwnerSet CurrOwners = getOwnersAtNode(CallEnterN); 853 OwnerSet ExitOwners = getOwnersAtNode(CallExitEndN); 854 855 // Owners in the current set may be purged from the analyzer later on. 856 // If a variable is dead (is not referenced directly or indirectly after 857 // some point), it will be removed from the Store before the end of its 858 // actual lifetime. 859 // This means that if the ownership status didn't change, CurrOwners 860 // must be a superset of, but not necessarily equal to ExitOwners. 861 return !llvm::set_is_subset(ExitOwners, CurrOwners); 862 } 863 864 static PathDiagnosticPieceRef emitNote(const ExplodedNode *N) { 865 PathDiagnosticLocation L = PathDiagnosticLocation::create( 866 N->getLocation(), 867 N->getState()->getStateManager().getContext().getSourceManager()); 868 return std::make_shared<PathDiagnosticEventPiece>( 869 L, "Returning without deallocating memory or storing the pointer for " 870 "later deallocation"); 871 } 872 873 PathDiagnosticPieceRef 874 maybeEmitNoteForObjCSelf(PathSensitiveBugReport &R, 875 const ObjCMethodCall &Call, 876 const ExplodedNode *N) override { 877 // TODO: Implement. 878 return nullptr; 879 } 880 881 PathDiagnosticPieceRef 882 maybeEmitNoteForCXXThis(PathSensitiveBugReport &R, 883 const CXXConstructorCall &Call, 884 const ExplodedNode *N) override { 885 // TODO: Implement. 886 return nullptr; 887 } 888 889 PathDiagnosticPieceRef 890 maybeEmitNoteForParameters(PathSensitiveBugReport &R, const CallEvent &Call, 891 const ExplodedNode *N) override { 892 // TODO: Factor the logic of "what constitutes as an entity being passed 893 // into a function call" out by reusing the code in 894 // NoStoreFuncVisitor::maybeEmitNoteForParameters, maybe by incorporating 895 // the printing technology in UninitializedObject's FieldChainInfo. 896 ArrayRef<ParmVarDecl *> Parameters = Call.parameters(); 897 for (unsigned I = 0; I < Call.getNumArgs() && I < Parameters.size(); ++I) { 898 SVal V = Call.getArgSVal(I); 899 if (V.getAsSymbol() == Sym) 900 return emitNote(N); 901 } 902 return nullptr; 903 } 904 905 public: 906 NoOwnershipChangeVisitor(SymbolRef Sym, const MallocChecker *Checker) 907 : NoStateChangeFuncVisitor(bugreporter::TrackingKind::Thorough), Sym(Sym), 908 Checker(*Checker) {} 909 910 void Profile(llvm::FoldingSetNodeID &ID) const override { 911 static int Tag = 0; 912 ID.AddPointer(&Tag); 913 ID.AddPointer(Sym); 914 } 915 }; 916 917 } // end anonymous namespace 918 919 //===----------------------------------------------------------------------===// 920 // Definition of MallocBugVisitor. 921 //===----------------------------------------------------------------------===// 922 923 namespace { 924 /// The bug visitor which allows us to print extra diagnostics along the 925 /// BugReport path. For example, showing the allocation site of the leaked 926 /// region. 927 class MallocBugVisitor final : public BugReporterVisitor { 928 protected: 929 enum NotificationMode { Normal, ReallocationFailed }; 930 931 // The allocated region symbol tracked by the main analysis. 932 SymbolRef Sym; 933 934 // The mode we are in, i.e. what kind of diagnostics will be emitted. 935 NotificationMode Mode; 936 937 // A symbol from when the primary region should have been reallocated. 938 SymbolRef FailedReallocSymbol; 939 940 // A C++ destructor stack frame in which memory was released. Used for 941 // miscellaneous false positive suppression. 942 const StackFrameContext *ReleaseDestructorLC; 943 944 bool IsLeak; 945 946 public: 947 MallocBugVisitor(SymbolRef S, bool isLeak = false) 948 : Sym(S), Mode(Normal), FailedReallocSymbol(nullptr), 949 ReleaseDestructorLC(nullptr), IsLeak(isLeak) {} 950 951 static void *getTag() { 952 static int Tag = 0; 953 return &Tag; 954 } 955 956 void Profile(llvm::FoldingSetNodeID &ID) const override { 957 ID.AddPointer(getTag()); 958 ID.AddPointer(Sym); 959 } 960 961 /// Did not track -> allocated. Other state (released) -> allocated. 962 static inline bool isAllocated(const RefState *RSCurr, const RefState *RSPrev, 963 const Stmt *Stmt) { 964 return (isa_and_nonnull<CallExpr, CXXNewExpr>(Stmt) && 965 (RSCurr && 966 (RSCurr->isAllocated() || RSCurr->isAllocatedOfSizeZero())) && 967 (!RSPrev || 968 !(RSPrev->isAllocated() || RSPrev->isAllocatedOfSizeZero()))); 969 } 970 971 /// Did not track -> released. Other state (allocated) -> released. 972 /// The statement associated with the release might be missing. 973 static inline bool isReleased(const RefState *RSCurr, const RefState *RSPrev, 974 const Stmt *Stmt) { 975 bool IsReleased = 976 (RSCurr && RSCurr->isReleased()) && (!RSPrev || !RSPrev->isReleased()); 977 assert(!IsReleased || (isa_and_nonnull<CallExpr, CXXDeleteExpr>(Stmt)) || 978 (!Stmt && RSCurr->getAllocationFamily() == AF_InnerBuffer)); 979 return IsReleased; 980 } 981 982 /// Did not track -> relinquished. Other state (allocated) -> relinquished. 983 static inline bool isRelinquished(const RefState *RSCurr, 984 const RefState *RSPrev, const Stmt *Stmt) { 985 return ( 986 isa_and_nonnull<CallExpr, ObjCMessageExpr, ObjCPropertyRefExpr>(Stmt) && 987 (RSCurr && RSCurr->isRelinquished()) && 988 (!RSPrev || !RSPrev->isRelinquished())); 989 } 990 991 /// If the expression is not a call, and the state change is 992 /// released -> allocated, it must be the realloc return value 993 /// check. If we have to handle more cases here, it might be cleaner just 994 /// to track this extra bit in the state itself. 995 static inline bool hasReallocFailed(const RefState *RSCurr, 996 const RefState *RSPrev, 997 const Stmt *Stmt) { 998 return ((!isa_and_nonnull<CallExpr>(Stmt)) && 999 (RSCurr && 1000 (RSCurr->isAllocated() || RSCurr->isAllocatedOfSizeZero())) && 1001 (RSPrev && 1002 !(RSPrev->isAllocated() || RSPrev->isAllocatedOfSizeZero()))); 1003 } 1004 1005 PathDiagnosticPieceRef VisitNode(const ExplodedNode *N, 1006 BugReporterContext &BRC, 1007 PathSensitiveBugReport &BR) override; 1008 1009 PathDiagnosticPieceRef getEndPath(BugReporterContext &BRC, 1010 const ExplodedNode *EndPathNode, 1011 PathSensitiveBugReport &BR) override { 1012 if (!IsLeak) 1013 return nullptr; 1014 1015 PathDiagnosticLocation L = BR.getLocation(); 1016 // Do not add the statement itself as a range in case of leak. 1017 return std::make_shared<PathDiagnosticEventPiece>(L, BR.getDescription(), 1018 false); 1019 } 1020 1021 private: 1022 class StackHintGeneratorForReallocationFailed 1023 : public StackHintGeneratorForSymbol { 1024 public: 1025 StackHintGeneratorForReallocationFailed(SymbolRef S, StringRef M) 1026 : StackHintGeneratorForSymbol(S, M) {} 1027 1028 std::string getMessageForArg(const Expr *ArgE, unsigned ArgIndex) override { 1029 // Printed parameters start at 1, not 0. 1030 ++ArgIndex; 1031 1032 SmallString<200> buf; 1033 llvm::raw_svector_ostream os(buf); 1034 1035 os << "Reallocation of " << ArgIndex << llvm::getOrdinalSuffix(ArgIndex) 1036 << " parameter failed"; 1037 1038 return std::string(os.str()); 1039 } 1040 1041 std::string getMessageForReturn(const CallExpr *CallExpr) override { 1042 return "Reallocation of returned value failed"; 1043 } 1044 }; 1045 }; 1046 } // end anonymous namespace 1047 1048 // A map from the freed symbol to the symbol representing the return value of 1049 // the free function. 1050 REGISTER_MAP_WITH_PROGRAMSTATE(FreeReturnValue, SymbolRef, SymbolRef) 1051 1052 namespace { 1053 class StopTrackingCallback final : public SymbolVisitor { 1054 ProgramStateRef state; 1055 1056 public: 1057 StopTrackingCallback(ProgramStateRef st) : state(std::move(st)) {} 1058 ProgramStateRef getState() const { return state; } 1059 1060 bool VisitSymbol(SymbolRef sym) override { 1061 state = state->remove<RegionState>(sym); 1062 return true; 1063 } 1064 }; 1065 } // end anonymous namespace 1066 1067 static bool isStandardNewDelete(const FunctionDecl *FD) { 1068 if (!FD) 1069 return false; 1070 1071 OverloadedOperatorKind Kind = FD->getOverloadedOperator(); 1072 if (Kind != OO_New && Kind != OO_Array_New && Kind != OO_Delete && 1073 Kind != OO_Array_Delete) 1074 return false; 1075 1076 // This is standard if and only if it's not defined in a user file. 1077 SourceLocation L = FD->getLocation(); 1078 // If the header for operator delete is not included, it's still defined 1079 // in an invalid source location. Check to make sure we don't crash. 1080 return !L.isValid() || 1081 FD->getASTContext().getSourceManager().isInSystemHeader(L); 1082 } 1083 1084 //===----------------------------------------------------------------------===// 1085 // Methods of MallocChecker and MallocBugVisitor. 1086 //===----------------------------------------------------------------------===// 1087 1088 bool MallocChecker::isFreeingOwnershipAttrCall(const FunctionDecl *Func) { 1089 if (Func->hasAttrs()) { 1090 for (const auto *I : Func->specific_attrs<OwnershipAttr>()) { 1091 OwnershipAttr::OwnershipKind OwnKind = I->getOwnKind(); 1092 if (OwnKind == OwnershipAttr::Takes || OwnKind == OwnershipAttr::Holds) 1093 return true; 1094 } 1095 } 1096 return false; 1097 } 1098 1099 bool MallocChecker::isFreeingCall(const CallEvent &Call) const { 1100 if (FreeingMemFnMap.lookup(Call) || ReallocatingMemFnMap.lookup(Call)) 1101 return true; 1102 1103 if (const auto *Func = dyn_cast_or_null<FunctionDecl>(Call.getDecl())) 1104 return isFreeingOwnershipAttrCall(Func); 1105 1106 return false; 1107 } 1108 1109 bool MallocChecker::isMemCall(const CallEvent &Call) const { 1110 if (FreeingMemFnMap.lookup(Call) || AllocatingMemFnMap.lookup(Call) || 1111 ReallocatingMemFnMap.lookup(Call)) 1112 return true; 1113 1114 if (!ShouldIncludeOwnershipAnnotatedFunctions) 1115 return false; 1116 1117 const auto *Func = dyn_cast<FunctionDecl>(Call.getDecl()); 1118 return Func && Func->hasAttr<OwnershipAttr>(); 1119 } 1120 1121 llvm::Optional<ProgramStateRef> 1122 MallocChecker::performKernelMalloc(const CallEvent &Call, CheckerContext &C, 1123 const ProgramStateRef &State) const { 1124 // 3-argument malloc(), as commonly used in {Free,Net,Open}BSD Kernels: 1125 // 1126 // void *malloc(unsigned long size, struct malloc_type *mtp, int flags); 1127 // 1128 // One of the possible flags is M_ZERO, which means 'give me back an 1129 // allocation which is already zeroed', like calloc. 1130 1131 // 2-argument kmalloc(), as used in the Linux kernel: 1132 // 1133 // void *kmalloc(size_t size, gfp_t flags); 1134 // 1135 // Has the similar flag value __GFP_ZERO. 1136 1137 // This logic is largely cloned from O_CREAT in UnixAPIChecker, maybe some 1138 // code could be shared. 1139 1140 ASTContext &Ctx = C.getASTContext(); 1141 llvm::Triple::OSType OS = Ctx.getTargetInfo().getTriple().getOS(); 1142 1143 if (!KernelZeroFlagVal) { 1144 if (OS == llvm::Triple::FreeBSD) 1145 KernelZeroFlagVal = 0x0100; 1146 else if (OS == llvm::Triple::NetBSD) 1147 KernelZeroFlagVal = 0x0002; 1148 else if (OS == llvm::Triple::OpenBSD) 1149 KernelZeroFlagVal = 0x0008; 1150 else if (OS == llvm::Triple::Linux) 1151 // __GFP_ZERO 1152 KernelZeroFlagVal = 0x8000; 1153 else 1154 // FIXME: We need a more general way of getting the M_ZERO value. 1155 // See also: O_CREAT in UnixAPIChecker.cpp. 1156 1157 // Fall back to normal malloc behavior on platforms where we don't 1158 // know M_ZERO. 1159 return std::nullopt; 1160 } 1161 1162 // We treat the last argument as the flags argument, and callers fall-back to 1163 // normal malloc on a None return. This works for the FreeBSD kernel malloc 1164 // as well as Linux kmalloc. 1165 if (Call.getNumArgs() < 2) 1166 return std::nullopt; 1167 1168 const Expr *FlagsEx = Call.getArgExpr(Call.getNumArgs() - 1); 1169 const SVal V = C.getSVal(FlagsEx); 1170 if (!isa<NonLoc>(V)) { 1171 // The case where 'V' can be a location can only be due to a bad header, 1172 // so in this case bail out. 1173 return std::nullopt; 1174 } 1175 1176 NonLoc Flags = V.castAs<NonLoc>(); 1177 NonLoc ZeroFlag = C.getSValBuilder() 1178 .makeIntVal(*KernelZeroFlagVal, FlagsEx->getType()) 1179 .castAs<NonLoc>(); 1180 SVal MaskedFlagsUC = C.getSValBuilder().evalBinOpNN(State, BO_And, 1181 Flags, ZeroFlag, 1182 FlagsEx->getType()); 1183 if (MaskedFlagsUC.isUnknownOrUndef()) 1184 return std::nullopt; 1185 DefinedSVal MaskedFlags = MaskedFlagsUC.castAs<DefinedSVal>(); 1186 1187 // Check if maskedFlags is non-zero. 1188 ProgramStateRef TrueState, FalseState; 1189 std::tie(TrueState, FalseState) = State->assume(MaskedFlags); 1190 1191 // If M_ZERO is set, treat this like calloc (initialized). 1192 if (TrueState && !FalseState) { 1193 SVal ZeroVal = C.getSValBuilder().makeZeroVal(Ctx.CharTy); 1194 return MallocMemAux(C, Call, Call.getArgExpr(0), ZeroVal, TrueState, 1195 AF_Malloc); 1196 } 1197 1198 return std::nullopt; 1199 } 1200 1201 SVal MallocChecker::evalMulForBufferSize(CheckerContext &C, const Expr *Blocks, 1202 const Expr *BlockBytes) { 1203 SValBuilder &SB = C.getSValBuilder(); 1204 SVal BlocksVal = C.getSVal(Blocks); 1205 SVal BlockBytesVal = C.getSVal(BlockBytes); 1206 ProgramStateRef State = C.getState(); 1207 SVal TotalSize = SB.evalBinOp(State, BO_Mul, BlocksVal, BlockBytesVal, 1208 SB.getContext().getSizeType()); 1209 return TotalSize; 1210 } 1211 1212 void MallocChecker::checkBasicAlloc(const CallEvent &Call, 1213 CheckerContext &C) const { 1214 ProgramStateRef State = C.getState(); 1215 State = MallocMemAux(C, Call, Call.getArgExpr(0), UndefinedVal(), State, 1216 AF_Malloc); 1217 State = ProcessZeroAllocCheck(Call, 0, State); 1218 C.addTransition(State); 1219 } 1220 1221 void MallocChecker::checkKernelMalloc(const CallEvent &Call, 1222 CheckerContext &C) const { 1223 ProgramStateRef State = C.getState(); 1224 llvm::Optional<ProgramStateRef> MaybeState = 1225 performKernelMalloc(Call, C, State); 1226 if (MaybeState) 1227 State = MaybeState.value(); 1228 else 1229 State = MallocMemAux(C, Call, Call.getArgExpr(0), UndefinedVal(), State, 1230 AF_Malloc); 1231 C.addTransition(State); 1232 } 1233 1234 static bool isStandardRealloc(const CallEvent &Call) { 1235 const FunctionDecl *FD = dyn_cast<FunctionDecl>(Call.getDecl()); 1236 assert(FD); 1237 ASTContext &AC = FD->getASTContext(); 1238 1239 if (isa<CXXMethodDecl>(FD)) 1240 return false; 1241 1242 return FD->getDeclaredReturnType().getDesugaredType(AC) == AC.VoidPtrTy && 1243 FD->getParamDecl(0)->getType().getDesugaredType(AC) == AC.VoidPtrTy && 1244 FD->getParamDecl(1)->getType().getDesugaredType(AC) == 1245 AC.getSizeType(); 1246 } 1247 1248 static bool isGRealloc(const CallEvent &Call) { 1249 const FunctionDecl *FD = dyn_cast<FunctionDecl>(Call.getDecl()); 1250 assert(FD); 1251 ASTContext &AC = FD->getASTContext(); 1252 1253 if (isa<CXXMethodDecl>(FD)) 1254 return false; 1255 1256 return FD->getDeclaredReturnType().getDesugaredType(AC) == AC.VoidPtrTy && 1257 FD->getParamDecl(0)->getType().getDesugaredType(AC) == AC.VoidPtrTy && 1258 FD->getParamDecl(1)->getType().getDesugaredType(AC) == 1259 AC.UnsignedLongTy; 1260 } 1261 1262 void MallocChecker::checkRealloc(const CallEvent &Call, CheckerContext &C, 1263 bool ShouldFreeOnFail) const { 1264 // HACK: CallDescription currently recognizes non-standard realloc functions 1265 // as standard because it doesn't check the type, or wether its a non-method 1266 // function. This should be solved by making CallDescription smarter. 1267 // Mind that this came from a bug report, and all other functions suffer from 1268 // this. 1269 // https://bugs.llvm.org/show_bug.cgi?id=46253 1270 if (!isStandardRealloc(Call) && !isGRealloc(Call)) 1271 return; 1272 ProgramStateRef State = C.getState(); 1273 State = ReallocMemAux(C, Call, ShouldFreeOnFail, State, AF_Malloc); 1274 State = ProcessZeroAllocCheck(Call, 1, State); 1275 C.addTransition(State); 1276 } 1277 1278 void MallocChecker::checkCalloc(const CallEvent &Call, 1279 CheckerContext &C) const { 1280 ProgramStateRef State = C.getState(); 1281 State = CallocMem(C, Call, State); 1282 State = ProcessZeroAllocCheck(Call, 0, State); 1283 State = ProcessZeroAllocCheck(Call, 1, State); 1284 C.addTransition(State); 1285 } 1286 1287 void MallocChecker::checkFree(const CallEvent &Call, CheckerContext &C) const { 1288 ProgramStateRef State = C.getState(); 1289 bool IsKnownToBeAllocatedMemory = false; 1290 if (suppressDeallocationsInSuspiciousContexts(Call, C)) 1291 return; 1292 State = FreeMemAux(C, Call, State, 0, false, IsKnownToBeAllocatedMemory, 1293 AF_Malloc); 1294 C.addTransition(State); 1295 } 1296 1297 void MallocChecker::checkAlloca(const CallEvent &Call, 1298 CheckerContext &C) const { 1299 ProgramStateRef State = C.getState(); 1300 State = MallocMemAux(C, Call, Call.getArgExpr(0), UndefinedVal(), State, 1301 AF_Alloca); 1302 State = ProcessZeroAllocCheck(Call, 0, State); 1303 C.addTransition(State); 1304 } 1305 1306 void MallocChecker::checkStrdup(const CallEvent &Call, 1307 CheckerContext &C) const { 1308 ProgramStateRef State = C.getState(); 1309 const auto *CE = dyn_cast_or_null<CallExpr>(Call.getOriginExpr()); 1310 if (!CE) 1311 return; 1312 State = MallocUpdateRefState(C, CE, State, AF_Malloc); 1313 1314 C.addTransition(State); 1315 } 1316 1317 void MallocChecker::checkIfNameIndex(const CallEvent &Call, 1318 CheckerContext &C) const { 1319 ProgramStateRef State = C.getState(); 1320 // Should we model this differently? We can allocate a fixed number of 1321 // elements with zeros in the last one. 1322 State = 1323 MallocMemAux(C, Call, UnknownVal(), UnknownVal(), State, AF_IfNameIndex); 1324 1325 C.addTransition(State); 1326 } 1327 1328 void MallocChecker::checkIfFreeNameIndex(const CallEvent &Call, 1329 CheckerContext &C) const { 1330 ProgramStateRef State = C.getState(); 1331 bool IsKnownToBeAllocatedMemory = false; 1332 State = FreeMemAux(C, Call, State, 0, false, IsKnownToBeAllocatedMemory, 1333 AF_IfNameIndex); 1334 C.addTransition(State); 1335 } 1336 1337 void MallocChecker::checkCXXNewOrCXXDelete(const CallEvent &Call, 1338 CheckerContext &C) const { 1339 ProgramStateRef State = C.getState(); 1340 bool IsKnownToBeAllocatedMemory = false; 1341 const auto *CE = dyn_cast_or_null<CallExpr>(Call.getOriginExpr()); 1342 if (!CE) 1343 return; 1344 1345 assert(isStandardNewDelete(Call)); 1346 1347 // Process direct calls to operator new/new[]/delete/delete[] functions 1348 // as distinct from new/new[]/delete/delete[] expressions that are 1349 // processed by the checkPostStmt callbacks for CXXNewExpr and 1350 // CXXDeleteExpr. 1351 const FunctionDecl *FD = C.getCalleeDecl(CE); 1352 switch (FD->getOverloadedOperator()) { 1353 case OO_New: 1354 State = 1355 MallocMemAux(C, Call, CE->getArg(0), UndefinedVal(), State, AF_CXXNew); 1356 State = ProcessZeroAllocCheck(Call, 0, State); 1357 break; 1358 case OO_Array_New: 1359 State = MallocMemAux(C, Call, CE->getArg(0), UndefinedVal(), State, 1360 AF_CXXNewArray); 1361 State = ProcessZeroAllocCheck(Call, 0, State); 1362 break; 1363 case OO_Delete: 1364 State = FreeMemAux(C, Call, State, 0, false, IsKnownToBeAllocatedMemory, 1365 AF_CXXNew); 1366 break; 1367 case OO_Array_Delete: 1368 State = FreeMemAux(C, Call, State, 0, false, IsKnownToBeAllocatedMemory, 1369 AF_CXXNewArray); 1370 break; 1371 default: 1372 llvm_unreachable("not a new/delete operator"); 1373 } 1374 1375 C.addTransition(State); 1376 } 1377 1378 void MallocChecker::checkGMalloc0(const CallEvent &Call, 1379 CheckerContext &C) const { 1380 ProgramStateRef State = C.getState(); 1381 SValBuilder &svalBuilder = C.getSValBuilder(); 1382 SVal zeroVal = svalBuilder.makeZeroVal(svalBuilder.getContext().CharTy); 1383 State = MallocMemAux(C, Call, Call.getArgExpr(0), zeroVal, State, AF_Malloc); 1384 State = ProcessZeroAllocCheck(Call, 0, State); 1385 C.addTransition(State); 1386 } 1387 1388 void MallocChecker::checkGMemdup(const CallEvent &Call, 1389 CheckerContext &C) const { 1390 ProgramStateRef State = C.getState(); 1391 State = 1392 MallocMemAux(C, Call, Call.getArgExpr(1), UnknownVal(), State, AF_Malloc); 1393 State = ProcessZeroAllocCheck(Call, 1, State); 1394 C.addTransition(State); 1395 } 1396 1397 void MallocChecker::checkGMallocN(const CallEvent &Call, 1398 CheckerContext &C) const { 1399 ProgramStateRef State = C.getState(); 1400 SVal Init = UndefinedVal(); 1401 SVal TotalSize = evalMulForBufferSize(C, Call.getArgExpr(0), Call.getArgExpr(1)); 1402 State = MallocMemAux(C, Call, TotalSize, Init, State, AF_Malloc); 1403 State = ProcessZeroAllocCheck(Call, 0, State); 1404 State = ProcessZeroAllocCheck(Call, 1, State); 1405 C.addTransition(State); 1406 } 1407 1408 void MallocChecker::checkGMallocN0(const CallEvent &Call, 1409 CheckerContext &C) const { 1410 ProgramStateRef State = C.getState(); 1411 SValBuilder &SB = C.getSValBuilder(); 1412 SVal Init = SB.makeZeroVal(SB.getContext().CharTy); 1413 SVal TotalSize = evalMulForBufferSize(C, Call.getArgExpr(0), Call.getArgExpr(1)); 1414 State = MallocMemAux(C, Call, TotalSize, Init, State, AF_Malloc); 1415 State = ProcessZeroAllocCheck(Call, 0, State); 1416 State = ProcessZeroAllocCheck(Call, 1, State); 1417 C.addTransition(State); 1418 } 1419 1420 void MallocChecker::checkReallocN(const CallEvent &Call, 1421 CheckerContext &C) const { 1422 ProgramStateRef State = C.getState(); 1423 State = ReallocMemAux(C, Call, /*ShouldFreeOnFail=*/false, State, AF_Malloc, 1424 /*SuffixWithN=*/true); 1425 State = ProcessZeroAllocCheck(Call, 1, State); 1426 State = ProcessZeroAllocCheck(Call, 2, State); 1427 C.addTransition(State); 1428 } 1429 1430 void MallocChecker::checkOwnershipAttr(const CallEvent &Call, 1431 CheckerContext &C) const { 1432 ProgramStateRef State = C.getState(); 1433 const auto *CE = dyn_cast_or_null<CallExpr>(Call.getOriginExpr()); 1434 if (!CE) 1435 return; 1436 const FunctionDecl *FD = C.getCalleeDecl(CE); 1437 if (!FD) 1438 return; 1439 if (ShouldIncludeOwnershipAnnotatedFunctions || 1440 ChecksEnabled[CK_MismatchedDeallocatorChecker]) { 1441 // Check all the attributes, if there are any. 1442 // There can be multiple of these attributes. 1443 if (FD->hasAttrs()) 1444 for (const auto *I : FD->specific_attrs<OwnershipAttr>()) { 1445 switch (I->getOwnKind()) { 1446 case OwnershipAttr::Returns: 1447 State = MallocMemReturnsAttr(C, Call, I, State); 1448 break; 1449 case OwnershipAttr::Takes: 1450 case OwnershipAttr::Holds: 1451 State = FreeMemAttr(C, Call, I, State); 1452 break; 1453 } 1454 } 1455 } 1456 C.addTransition(State); 1457 } 1458 1459 void MallocChecker::checkPostCall(const CallEvent &Call, 1460 CheckerContext &C) const { 1461 if (C.wasInlined) 1462 return; 1463 if (!Call.getOriginExpr()) 1464 return; 1465 1466 ProgramStateRef State = C.getState(); 1467 1468 if (const CheckFn *Callback = FreeingMemFnMap.lookup(Call)) { 1469 (*Callback)(this, Call, C); 1470 return; 1471 } 1472 1473 if (const CheckFn *Callback = AllocatingMemFnMap.lookup(Call)) { 1474 (*Callback)(this, Call, C); 1475 return; 1476 } 1477 1478 if (const CheckFn *Callback = ReallocatingMemFnMap.lookup(Call)) { 1479 (*Callback)(this, Call, C); 1480 return; 1481 } 1482 1483 if (isStandardNewDelete(Call)) { 1484 checkCXXNewOrCXXDelete(Call, C); 1485 return; 1486 } 1487 1488 checkOwnershipAttr(Call, C); 1489 } 1490 1491 // Performs a 0-sized allocations check. 1492 ProgramStateRef MallocChecker::ProcessZeroAllocCheck( 1493 const CallEvent &Call, const unsigned IndexOfSizeArg, ProgramStateRef State, 1494 Optional<SVal> RetVal) { 1495 if (!State) 1496 return nullptr; 1497 1498 if (!RetVal) 1499 RetVal = Call.getReturnValue(); 1500 1501 const Expr *Arg = nullptr; 1502 1503 if (const CallExpr *CE = dyn_cast<CallExpr>(Call.getOriginExpr())) { 1504 Arg = CE->getArg(IndexOfSizeArg); 1505 } else if (const CXXNewExpr *NE = 1506 dyn_cast<CXXNewExpr>(Call.getOriginExpr())) { 1507 if (NE->isArray()) { 1508 Arg = *NE->getArraySize(); 1509 } else { 1510 return State; 1511 } 1512 } else 1513 llvm_unreachable("not a CallExpr or CXXNewExpr"); 1514 1515 assert(Arg); 1516 1517 auto DefArgVal = 1518 State->getSVal(Arg, Call.getLocationContext()).getAs<DefinedSVal>(); 1519 1520 if (!DefArgVal) 1521 return State; 1522 1523 // Check if the allocation size is 0. 1524 ProgramStateRef TrueState, FalseState; 1525 SValBuilder &SvalBuilder = State->getStateManager().getSValBuilder(); 1526 DefinedSVal Zero = 1527 SvalBuilder.makeZeroVal(Arg->getType()).castAs<DefinedSVal>(); 1528 1529 std::tie(TrueState, FalseState) = 1530 State->assume(SvalBuilder.evalEQ(State, *DefArgVal, Zero)); 1531 1532 if (TrueState && !FalseState) { 1533 SymbolRef Sym = RetVal->getAsLocSymbol(); 1534 if (!Sym) 1535 return State; 1536 1537 const RefState *RS = State->get<RegionState>(Sym); 1538 if (RS) { 1539 if (RS->isAllocated()) 1540 return TrueState->set<RegionState>(Sym, 1541 RefState::getAllocatedOfSizeZero(RS)); 1542 else 1543 return State; 1544 } else { 1545 // Case of zero-size realloc. Historically 'realloc(ptr, 0)' is treated as 1546 // 'free(ptr)' and the returned value from 'realloc(ptr, 0)' is not 1547 // tracked. Add zero-reallocated Sym to the state to catch references 1548 // to zero-allocated memory. 1549 return TrueState->add<ReallocSizeZeroSymbols>(Sym); 1550 } 1551 } 1552 1553 // Assume the value is non-zero going forward. 1554 assert(FalseState); 1555 return FalseState; 1556 } 1557 1558 static QualType getDeepPointeeType(QualType T) { 1559 QualType Result = T, PointeeType = T->getPointeeType(); 1560 while (!PointeeType.isNull()) { 1561 Result = PointeeType; 1562 PointeeType = PointeeType->getPointeeType(); 1563 } 1564 return Result; 1565 } 1566 1567 /// \returns true if the constructor invoked by \p NE has an argument of a 1568 /// pointer/reference to a record type. 1569 static bool hasNonTrivialConstructorCall(const CXXNewExpr *NE) { 1570 1571 const CXXConstructExpr *ConstructE = NE->getConstructExpr(); 1572 if (!ConstructE) 1573 return false; 1574 1575 if (!NE->getAllocatedType()->getAsCXXRecordDecl()) 1576 return false; 1577 1578 const CXXConstructorDecl *CtorD = ConstructE->getConstructor(); 1579 1580 // Iterate over the constructor parameters. 1581 for (const auto *CtorParam : CtorD->parameters()) { 1582 1583 QualType CtorParamPointeeT = CtorParam->getType()->getPointeeType(); 1584 if (CtorParamPointeeT.isNull()) 1585 continue; 1586 1587 CtorParamPointeeT = getDeepPointeeType(CtorParamPointeeT); 1588 1589 if (CtorParamPointeeT->getAsCXXRecordDecl()) 1590 return true; 1591 } 1592 1593 return false; 1594 } 1595 1596 ProgramStateRef 1597 MallocChecker::processNewAllocation(const CXXAllocatorCall &Call, 1598 CheckerContext &C, 1599 AllocationFamily Family) const { 1600 if (!isStandardNewDelete(Call)) 1601 return nullptr; 1602 1603 const CXXNewExpr *NE = Call.getOriginExpr(); 1604 const ParentMap &PM = C.getLocationContext()->getParentMap(); 1605 ProgramStateRef State = C.getState(); 1606 1607 // Non-trivial constructors have a chance to escape 'this', but marking all 1608 // invocations of trivial constructors as escaped would cause too great of 1609 // reduction of true positives, so let's just do that for constructors that 1610 // have an argument of a pointer-to-record type. 1611 if (!PM.isConsumedExpr(NE) && hasNonTrivialConstructorCall(NE)) 1612 return State; 1613 1614 // The return value from operator new is bound to a specified initialization 1615 // value (if any) and we don't want to loose this value. So we call 1616 // MallocUpdateRefState() instead of MallocMemAux() which breaks the 1617 // existing binding. 1618 SVal Target = Call.getObjectUnderConstruction(); 1619 State = MallocUpdateRefState(C, NE, State, Family, Target); 1620 State = ProcessZeroAllocCheck(Call, 0, State, Target); 1621 return State; 1622 } 1623 1624 void MallocChecker::checkNewAllocator(const CXXAllocatorCall &Call, 1625 CheckerContext &C) const { 1626 if (!C.wasInlined) { 1627 ProgramStateRef State = processNewAllocation( 1628 Call, C, 1629 (Call.getOriginExpr()->isArray() ? AF_CXXNewArray : AF_CXXNew)); 1630 C.addTransition(State); 1631 } 1632 } 1633 1634 static bool isKnownDeallocObjCMethodName(const ObjCMethodCall &Call) { 1635 // If the first selector piece is one of the names below, assume that the 1636 // object takes ownership of the memory, promising to eventually deallocate it 1637 // with free(). 1638 // Ex: [NSData dataWithBytesNoCopy:bytes length:10]; 1639 // (...unless a 'freeWhenDone' parameter is false, but that's checked later.) 1640 StringRef FirstSlot = Call.getSelector().getNameForSlot(0); 1641 return FirstSlot == "dataWithBytesNoCopy" || 1642 FirstSlot == "initWithBytesNoCopy" || 1643 FirstSlot == "initWithCharactersNoCopy"; 1644 } 1645 1646 static std::optional<bool> getFreeWhenDoneArg(const ObjCMethodCall &Call) { 1647 Selector S = Call.getSelector(); 1648 1649 // FIXME: We should not rely on fully-constrained symbols being folded. 1650 for (unsigned i = 1; i < S.getNumArgs(); ++i) 1651 if (S.getNameForSlot(i).equals("freeWhenDone")) 1652 return !Call.getArgSVal(i).isZeroConstant(); 1653 1654 return std::nullopt; 1655 } 1656 1657 void MallocChecker::checkPostObjCMessage(const ObjCMethodCall &Call, 1658 CheckerContext &C) const { 1659 if (C.wasInlined) 1660 return; 1661 1662 if (!isKnownDeallocObjCMethodName(Call)) 1663 return; 1664 1665 if (std::optional<bool> FreeWhenDone = getFreeWhenDoneArg(Call)) 1666 if (!*FreeWhenDone) 1667 return; 1668 1669 if (Call.hasNonZeroCallbackArg()) 1670 return; 1671 1672 bool IsKnownToBeAllocatedMemory; 1673 ProgramStateRef State = 1674 FreeMemAux(C, Call.getArgExpr(0), Call, C.getState(), 1675 /*Hold=*/true, IsKnownToBeAllocatedMemory, AF_Malloc, 1676 /*ReturnsNullOnFailure=*/true); 1677 1678 C.addTransition(State); 1679 } 1680 1681 ProgramStateRef 1682 MallocChecker::MallocMemReturnsAttr(CheckerContext &C, const CallEvent &Call, 1683 const OwnershipAttr *Att, 1684 ProgramStateRef State) const { 1685 if (!State) 1686 return nullptr; 1687 1688 if (Att->getModule()->getName() != "malloc") 1689 return nullptr; 1690 1691 OwnershipAttr::args_iterator I = Att->args_begin(), E = Att->args_end(); 1692 if (I != E) { 1693 return MallocMemAux(C, Call, Call.getArgExpr(I->getASTIndex()), 1694 UndefinedVal(), State, AF_Malloc); 1695 } 1696 return MallocMemAux(C, Call, UnknownVal(), UndefinedVal(), State, AF_Malloc); 1697 } 1698 1699 ProgramStateRef MallocChecker::MallocMemAux(CheckerContext &C, 1700 const CallEvent &Call, 1701 const Expr *SizeEx, SVal Init, 1702 ProgramStateRef State, 1703 AllocationFamily Family) { 1704 if (!State) 1705 return nullptr; 1706 1707 assert(SizeEx); 1708 return MallocMemAux(C, Call, C.getSVal(SizeEx), Init, State, Family); 1709 } 1710 1711 ProgramStateRef MallocChecker::MallocMemAux(CheckerContext &C, 1712 const CallEvent &Call, SVal Size, 1713 SVal Init, ProgramStateRef State, 1714 AllocationFamily Family) { 1715 if (!State) 1716 return nullptr; 1717 1718 const Expr *CE = Call.getOriginExpr(); 1719 1720 // We expect the malloc functions to return a pointer. 1721 if (!Loc::isLocType(CE->getType())) 1722 return nullptr; 1723 1724 // Bind the return value to the symbolic value from the heap region. 1725 // TODO: We could rewrite post visit to eval call; 'malloc' does not have 1726 // side effects other than what we model here. 1727 unsigned Count = C.blockCount(); 1728 SValBuilder &svalBuilder = C.getSValBuilder(); 1729 const LocationContext *LCtx = C.getPredecessor()->getLocationContext(); 1730 DefinedSVal RetVal = svalBuilder.getConjuredHeapSymbolVal(CE, LCtx, Count) 1731 .castAs<DefinedSVal>(); 1732 State = State->BindExpr(CE, C.getLocationContext(), RetVal); 1733 1734 // Fill the region with the initialization value. 1735 State = State->bindDefaultInitial(RetVal, Init, LCtx); 1736 1737 // If Size is somehow undefined at this point, this line prevents a crash. 1738 if (Size.isUndef()) 1739 Size = UnknownVal(); 1740 1741 // Set the region's extent. 1742 State = setDynamicExtent(State, RetVal.getAsRegion(), 1743 Size.castAs<DefinedOrUnknownSVal>(), svalBuilder); 1744 1745 return MallocUpdateRefState(C, CE, State, Family); 1746 } 1747 1748 static ProgramStateRef MallocUpdateRefState(CheckerContext &C, const Expr *E, 1749 ProgramStateRef State, 1750 AllocationFamily Family, 1751 Optional<SVal> RetVal) { 1752 if (!State) 1753 return nullptr; 1754 1755 // Get the return value. 1756 if (!RetVal) 1757 RetVal = C.getSVal(E); 1758 1759 // We expect the malloc functions to return a pointer. 1760 if (!RetVal->getAs<Loc>()) 1761 return nullptr; 1762 1763 SymbolRef Sym = RetVal->getAsLocSymbol(); 1764 // This is a return value of a function that was not inlined, such as malloc() 1765 // or new(). We've checked that in the caller. Therefore, it must be a symbol. 1766 assert(Sym); 1767 1768 // Set the symbol's state to Allocated. 1769 return State->set<RegionState>(Sym, RefState::getAllocated(Family, E)); 1770 } 1771 1772 ProgramStateRef MallocChecker::FreeMemAttr(CheckerContext &C, 1773 const CallEvent &Call, 1774 const OwnershipAttr *Att, 1775 ProgramStateRef State) const { 1776 if (!State) 1777 return nullptr; 1778 1779 if (Att->getModule()->getName() != "malloc") 1780 return nullptr; 1781 1782 bool IsKnownToBeAllocated = false; 1783 1784 for (const auto &Arg : Att->args()) { 1785 ProgramStateRef StateI = 1786 FreeMemAux(C, Call, State, Arg.getASTIndex(), 1787 Att->getOwnKind() == OwnershipAttr::Holds, 1788 IsKnownToBeAllocated, AF_Malloc); 1789 if (StateI) 1790 State = StateI; 1791 } 1792 return State; 1793 } 1794 1795 ProgramStateRef MallocChecker::FreeMemAux(CheckerContext &C, 1796 const CallEvent &Call, 1797 ProgramStateRef State, unsigned Num, 1798 bool Hold, bool &IsKnownToBeAllocated, 1799 AllocationFamily Family, 1800 bool ReturnsNullOnFailure) const { 1801 if (!State) 1802 return nullptr; 1803 1804 if (Call.getNumArgs() < (Num + 1)) 1805 return nullptr; 1806 1807 return FreeMemAux(C, Call.getArgExpr(Num), Call, State, Hold, 1808 IsKnownToBeAllocated, Family, ReturnsNullOnFailure); 1809 } 1810 1811 /// Checks if the previous call to free on the given symbol failed - if free 1812 /// failed, returns true. Also, returns the corresponding return value symbol. 1813 static bool didPreviousFreeFail(ProgramStateRef State, 1814 SymbolRef Sym, SymbolRef &RetStatusSymbol) { 1815 const SymbolRef *Ret = State->get<FreeReturnValue>(Sym); 1816 if (Ret) { 1817 assert(*Ret && "We should not store the null return symbol"); 1818 ConstraintManager &CMgr = State->getConstraintManager(); 1819 ConditionTruthVal FreeFailed = CMgr.isNull(State, *Ret); 1820 RetStatusSymbol = *Ret; 1821 return FreeFailed.isConstrainedTrue(); 1822 } 1823 return false; 1824 } 1825 1826 static bool printMemFnName(raw_ostream &os, CheckerContext &C, const Expr *E) { 1827 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) { 1828 // FIXME: This doesn't handle indirect calls. 1829 const FunctionDecl *FD = CE->getDirectCallee(); 1830 if (!FD) 1831 return false; 1832 1833 os << *FD; 1834 if (!FD->isOverloadedOperator()) 1835 os << "()"; 1836 return true; 1837 } 1838 1839 if (const ObjCMessageExpr *Msg = dyn_cast<ObjCMessageExpr>(E)) { 1840 if (Msg->isInstanceMessage()) 1841 os << "-"; 1842 else 1843 os << "+"; 1844 Msg->getSelector().print(os); 1845 return true; 1846 } 1847 1848 if (const CXXNewExpr *NE = dyn_cast<CXXNewExpr>(E)) { 1849 os << "'" 1850 << getOperatorSpelling(NE->getOperatorNew()->getOverloadedOperator()) 1851 << "'"; 1852 return true; 1853 } 1854 1855 if (const CXXDeleteExpr *DE = dyn_cast<CXXDeleteExpr>(E)) { 1856 os << "'" 1857 << getOperatorSpelling(DE->getOperatorDelete()->getOverloadedOperator()) 1858 << "'"; 1859 return true; 1860 } 1861 1862 return false; 1863 } 1864 1865 static void printExpectedAllocName(raw_ostream &os, AllocationFamily Family) { 1866 1867 switch(Family) { 1868 case AF_Malloc: os << "malloc()"; return; 1869 case AF_CXXNew: os << "'new'"; return; 1870 case AF_CXXNewArray: os << "'new[]'"; return; 1871 case AF_IfNameIndex: os << "'if_nameindex()'"; return; 1872 case AF_InnerBuffer: os << "container-specific allocator"; return; 1873 case AF_Alloca: 1874 case AF_None: llvm_unreachable("not a deallocation expression"); 1875 } 1876 } 1877 1878 static void printExpectedDeallocName(raw_ostream &os, AllocationFamily Family) { 1879 switch(Family) { 1880 case AF_Malloc: os << "free()"; return; 1881 case AF_CXXNew: os << "'delete'"; return; 1882 case AF_CXXNewArray: os << "'delete[]'"; return; 1883 case AF_IfNameIndex: os << "'if_freenameindex()'"; return; 1884 case AF_InnerBuffer: os << "container-specific deallocator"; return; 1885 case AF_Alloca: 1886 case AF_None: llvm_unreachable("suspicious argument"); 1887 } 1888 } 1889 1890 ProgramStateRef MallocChecker::FreeMemAux( 1891 CheckerContext &C, const Expr *ArgExpr, const CallEvent &Call, 1892 ProgramStateRef State, bool Hold, bool &IsKnownToBeAllocated, 1893 AllocationFamily Family, bool ReturnsNullOnFailure) const { 1894 1895 if (!State) 1896 return nullptr; 1897 1898 SVal ArgVal = C.getSVal(ArgExpr); 1899 if (!isa<DefinedOrUnknownSVal>(ArgVal)) 1900 return nullptr; 1901 DefinedOrUnknownSVal location = ArgVal.castAs<DefinedOrUnknownSVal>(); 1902 1903 // Check for null dereferences. 1904 if (!isa<Loc>(location)) 1905 return nullptr; 1906 1907 // The explicit NULL case, no operation is performed. 1908 ProgramStateRef notNullState, nullState; 1909 std::tie(notNullState, nullState) = State->assume(location); 1910 if (nullState && !notNullState) 1911 return nullptr; 1912 1913 // Unknown values could easily be okay 1914 // Undefined values are handled elsewhere 1915 if (ArgVal.isUnknownOrUndef()) 1916 return nullptr; 1917 1918 const MemRegion *R = ArgVal.getAsRegion(); 1919 const Expr *ParentExpr = Call.getOriginExpr(); 1920 1921 // NOTE: We detected a bug, but the checker under whose name we would emit the 1922 // error could be disabled. Generally speaking, the MallocChecker family is an 1923 // integral part of the Static Analyzer, and disabling any part of it should 1924 // only be done under exceptional circumstances, such as frequent false 1925 // positives. If this is the case, we can reasonably believe that there are 1926 // serious faults in our understanding of the source code, and even if we 1927 // don't emit an warning, we should terminate further analysis with a sink 1928 // node. 1929 1930 // Nonlocs can't be freed, of course. 1931 // Non-region locations (labels and fixed addresses) also shouldn't be freed. 1932 if (!R) { 1933 // Exception: 1934 // If the macro ZERO_SIZE_PTR is defined, this could be a kernel source 1935 // code. In that case, the ZERO_SIZE_PTR defines a special value used for a 1936 // zero-sized memory block which is allowed to be freed, despite not being a 1937 // null pointer. 1938 if (Family != AF_Malloc || !isArgZERO_SIZE_PTR(State, C, ArgVal)) 1939 HandleNonHeapDealloc(C, ArgVal, ArgExpr->getSourceRange(), ParentExpr, 1940 Family); 1941 return nullptr; 1942 } 1943 1944 R = R->StripCasts(); 1945 1946 // Blocks might show up as heap data, but should not be free()d 1947 if (isa<BlockDataRegion>(R)) { 1948 HandleNonHeapDealloc(C, ArgVal, ArgExpr->getSourceRange(), ParentExpr, 1949 Family); 1950 return nullptr; 1951 } 1952 1953 const MemSpaceRegion *MS = R->getMemorySpace(); 1954 1955 // Parameters, locals, statics, globals, and memory returned by 1956 // __builtin_alloca() shouldn't be freed. 1957 if (!isa<UnknownSpaceRegion, HeapSpaceRegion>(MS)) { 1958 // FIXME: at the time this code was written, malloc() regions were 1959 // represented by conjured symbols, which are all in UnknownSpaceRegion. 1960 // This means that there isn't actually anything from HeapSpaceRegion 1961 // that should be freed, even though we allow it here. 1962 // Of course, free() can work on memory allocated outside the current 1963 // function, so UnknownSpaceRegion is always a possibility. 1964 // False negatives are better than false positives. 1965 1966 if (isa<AllocaRegion>(R)) 1967 HandleFreeAlloca(C, ArgVal, ArgExpr->getSourceRange()); 1968 else 1969 HandleNonHeapDealloc(C, ArgVal, ArgExpr->getSourceRange(), ParentExpr, 1970 Family); 1971 1972 return nullptr; 1973 } 1974 1975 const SymbolicRegion *SrBase = dyn_cast<SymbolicRegion>(R->getBaseRegion()); 1976 // Various cases could lead to non-symbol values here. 1977 // For now, ignore them. 1978 if (!SrBase) 1979 return nullptr; 1980 1981 SymbolRef SymBase = SrBase->getSymbol(); 1982 const RefState *RsBase = State->get<RegionState>(SymBase); 1983 SymbolRef PreviousRetStatusSymbol = nullptr; 1984 1985 IsKnownToBeAllocated = 1986 RsBase && (RsBase->isAllocated() || RsBase->isAllocatedOfSizeZero()); 1987 1988 if (RsBase) { 1989 1990 // Memory returned by alloca() shouldn't be freed. 1991 if (RsBase->getAllocationFamily() == AF_Alloca) { 1992 HandleFreeAlloca(C, ArgVal, ArgExpr->getSourceRange()); 1993 return nullptr; 1994 } 1995 1996 // Check for double free first. 1997 if ((RsBase->isReleased() || RsBase->isRelinquished()) && 1998 !didPreviousFreeFail(State, SymBase, PreviousRetStatusSymbol)) { 1999 HandleDoubleFree(C, ParentExpr->getSourceRange(), RsBase->isReleased(), 2000 SymBase, PreviousRetStatusSymbol); 2001 return nullptr; 2002 2003 // If the pointer is allocated or escaped, but we are now trying to free it, 2004 // check that the call to free is proper. 2005 } else if (RsBase->isAllocated() || RsBase->isAllocatedOfSizeZero() || 2006 RsBase->isEscaped()) { 2007 2008 // Check if an expected deallocation function matches the real one. 2009 bool DeallocMatchesAlloc = RsBase->getAllocationFamily() == Family; 2010 if (!DeallocMatchesAlloc) { 2011 HandleMismatchedDealloc(C, ArgExpr->getSourceRange(), ParentExpr, 2012 RsBase, SymBase, Hold); 2013 return nullptr; 2014 } 2015 2016 // Check if the memory location being freed is the actual location 2017 // allocated, or an offset. 2018 RegionOffset Offset = R->getAsOffset(); 2019 if (Offset.isValid() && 2020 !Offset.hasSymbolicOffset() && 2021 Offset.getOffset() != 0) { 2022 const Expr *AllocExpr = cast<Expr>(RsBase->getStmt()); 2023 HandleOffsetFree(C, ArgVal, ArgExpr->getSourceRange(), ParentExpr, 2024 Family, AllocExpr); 2025 return nullptr; 2026 } 2027 } 2028 } 2029 2030 if (SymBase->getType()->isFunctionPointerType()) { 2031 HandleFunctionPtrFree(C, ArgVal, ArgExpr->getSourceRange(), ParentExpr, 2032 Family); 2033 return nullptr; 2034 } 2035 2036 // Clean out the info on previous call to free return info. 2037 State = State->remove<FreeReturnValue>(SymBase); 2038 2039 // Keep track of the return value. If it is NULL, we will know that free 2040 // failed. 2041 if (ReturnsNullOnFailure) { 2042 SVal RetVal = C.getSVal(ParentExpr); 2043 SymbolRef RetStatusSymbol = RetVal.getAsSymbol(); 2044 if (RetStatusSymbol) { 2045 C.getSymbolManager().addSymbolDependency(SymBase, RetStatusSymbol); 2046 State = State->set<FreeReturnValue>(SymBase, RetStatusSymbol); 2047 } 2048 } 2049 2050 // If we don't know anything about this symbol, a free on it may be totally 2051 // valid. If this is the case, lets assume that the allocation family of the 2052 // freeing function is the same as the symbols allocation family, and go with 2053 // that. 2054 assert(!RsBase || (RsBase && RsBase->getAllocationFamily() == Family)); 2055 2056 // Normal free. 2057 if (Hold) 2058 return State->set<RegionState>(SymBase, 2059 RefState::getRelinquished(Family, 2060 ParentExpr)); 2061 2062 return State->set<RegionState>(SymBase, 2063 RefState::getReleased(Family, ParentExpr)); 2064 } 2065 2066 Optional<MallocChecker::CheckKind> 2067 MallocChecker::getCheckIfTracked(AllocationFamily Family, 2068 bool IsALeakCheck) const { 2069 switch (Family) { 2070 case AF_Malloc: 2071 case AF_Alloca: 2072 case AF_IfNameIndex: { 2073 if (ChecksEnabled[CK_MallocChecker]) 2074 return CK_MallocChecker; 2075 return std::nullopt; 2076 } 2077 case AF_CXXNew: 2078 case AF_CXXNewArray: { 2079 if (IsALeakCheck) { 2080 if (ChecksEnabled[CK_NewDeleteLeaksChecker]) 2081 return CK_NewDeleteLeaksChecker; 2082 } 2083 else { 2084 if (ChecksEnabled[CK_NewDeleteChecker]) 2085 return CK_NewDeleteChecker; 2086 } 2087 return std::nullopt; 2088 } 2089 case AF_InnerBuffer: { 2090 if (ChecksEnabled[CK_InnerPointerChecker]) 2091 return CK_InnerPointerChecker; 2092 return std::nullopt; 2093 } 2094 case AF_None: { 2095 llvm_unreachable("no family"); 2096 } 2097 } 2098 llvm_unreachable("unhandled family"); 2099 } 2100 2101 Optional<MallocChecker::CheckKind> 2102 MallocChecker::getCheckIfTracked(CheckerContext &C, SymbolRef Sym, 2103 bool IsALeakCheck) const { 2104 if (C.getState()->contains<ReallocSizeZeroSymbols>(Sym)) 2105 return CK_MallocChecker; 2106 2107 const RefState *RS = C.getState()->get<RegionState>(Sym); 2108 assert(RS); 2109 return getCheckIfTracked(RS->getAllocationFamily(), IsALeakCheck); 2110 } 2111 2112 bool MallocChecker::SummarizeValue(raw_ostream &os, SVal V) { 2113 if (Optional<nonloc::ConcreteInt> IntVal = V.getAs<nonloc::ConcreteInt>()) 2114 os << "an integer (" << IntVal->getValue() << ")"; 2115 else if (Optional<loc::ConcreteInt> ConstAddr = V.getAs<loc::ConcreteInt>()) 2116 os << "a constant address (" << ConstAddr->getValue() << ")"; 2117 else if (Optional<loc::GotoLabel> Label = V.getAs<loc::GotoLabel>()) 2118 os << "the address of the label '" << Label->getLabel()->getName() << "'"; 2119 else 2120 return false; 2121 2122 return true; 2123 } 2124 2125 bool MallocChecker::SummarizeRegion(raw_ostream &os, 2126 const MemRegion *MR) { 2127 switch (MR->getKind()) { 2128 case MemRegion::FunctionCodeRegionKind: { 2129 const NamedDecl *FD = cast<FunctionCodeRegion>(MR)->getDecl(); 2130 if (FD) 2131 os << "the address of the function '" << *FD << '\''; 2132 else 2133 os << "the address of a function"; 2134 return true; 2135 } 2136 case MemRegion::BlockCodeRegionKind: 2137 os << "block text"; 2138 return true; 2139 case MemRegion::BlockDataRegionKind: 2140 // FIXME: where the block came from? 2141 os << "a block"; 2142 return true; 2143 default: { 2144 const MemSpaceRegion *MS = MR->getMemorySpace(); 2145 2146 if (isa<StackLocalsSpaceRegion>(MS)) { 2147 const VarRegion *VR = dyn_cast<VarRegion>(MR); 2148 const VarDecl *VD; 2149 if (VR) 2150 VD = VR->getDecl(); 2151 else 2152 VD = nullptr; 2153 2154 if (VD) 2155 os << "the address of the local variable '" << VD->getName() << "'"; 2156 else 2157 os << "the address of a local stack variable"; 2158 return true; 2159 } 2160 2161 if (isa<StackArgumentsSpaceRegion>(MS)) { 2162 const VarRegion *VR = dyn_cast<VarRegion>(MR); 2163 const VarDecl *VD; 2164 if (VR) 2165 VD = VR->getDecl(); 2166 else 2167 VD = nullptr; 2168 2169 if (VD) 2170 os << "the address of the parameter '" << VD->getName() << "'"; 2171 else 2172 os << "the address of a parameter"; 2173 return true; 2174 } 2175 2176 if (isa<GlobalsSpaceRegion>(MS)) { 2177 const VarRegion *VR = dyn_cast<VarRegion>(MR); 2178 const VarDecl *VD; 2179 if (VR) 2180 VD = VR->getDecl(); 2181 else 2182 VD = nullptr; 2183 2184 if (VD) { 2185 if (VD->isStaticLocal()) 2186 os << "the address of the static variable '" << VD->getName() << "'"; 2187 else 2188 os << "the address of the global variable '" << VD->getName() << "'"; 2189 } else 2190 os << "the address of a global variable"; 2191 return true; 2192 } 2193 2194 return false; 2195 } 2196 } 2197 } 2198 2199 void MallocChecker::HandleNonHeapDealloc(CheckerContext &C, SVal ArgVal, 2200 SourceRange Range, 2201 const Expr *DeallocExpr, 2202 AllocationFamily Family) const { 2203 2204 if (!ChecksEnabled[CK_MallocChecker] && !ChecksEnabled[CK_NewDeleteChecker]) { 2205 C.addSink(); 2206 return; 2207 } 2208 2209 Optional<MallocChecker::CheckKind> CheckKind = getCheckIfTracked(Family); 2210 if (!CheckKind) 2211 return; 2212 2213 if (ExplodedNode *N = C.generateErrorNode()) { 2214 if (!BT_BadFree[*CheckKind]) 2215 BT_BadFree[*CheckKind].reset(new BugType( 2216 CheckNames[*CheckKind], "Bad free", categories::MemoryError)); 2217 2218 SmallString<100> buf; 2219 llvm::raw_svector_ostream os(buf); 2220 2221 const MemRegion *MR = ArgVal.getAsRegion(); 2222 while (const ElementRegion *ER = dyn_cast_or_null<ElementRegion>(MR)) 2223 MR = ER->getSuperRegion(); 2224 2225 os << "Argument to "; 2226 if (!printMemFnName(os, C, DeallocExpr)) 2227 os << "deallocator"; 2228 2229 os << " is "; 2230 bool Summarized = MR ? SummarizeRegion(os, MR) 2231 : SummarizeValue(os, ArgVal); 2232 if (Summarized) 2233 os << ", which is not memory allocated by "; 2234 else 2235 os << "not memory allocated by "; 2236 2237 printExpectedAllocName(os, Family); 2238 2239 auto R = std::make_unique<PathSensitiveBugReport>(*BT_BadFree[*CheckKind], 2240 os.str(), N); 2241 R->markInteresting(MR); 2242 R->addRange(Range); 2243 C.emitReport(std::move(R)); 2244 } 2245 } 2246 2247 void MallocChecker::HandleFreeAlloca(CheckerContext &C, SVal ArgVal, 2248 SourceRange Range) const { 2249 2250 std::optional<MallocChecker::CheckKind> CheckKind; 2251 2252 if (ChecksEnabled[CK_MallocChecker]) 2253 CheckKind = CK_MallocChecker; 2254 else if (ChecksEnabled[CK_MismatchedDeallocatorChecker]) 2255 CheckKind = CK_MismatchedDeallocatorChecker; 2256 else { 2257 C.addSink(); 2258 return; 2259 } 2260 2261 if (ExplodedNode *N = C.generateErrorNode()) { 2262 if (!BT_FreeAlloca[*CheckKind]) 2263 BT_FreeAlloca[*CheckKind].reset(new BugType( 2264 CheckNames[*CheckKind], "Free alloca()", categories::MemoryError)); 2265 2266 auto R = std::make_unique<PathSensitiveBugReport>( 2267 *BT_FreeAlloca[*CheckKind], 2268 "Memory allocated by alloca() should not be deallocated", N); 2269 R->markInteresting(ArgVal.getAsRegion()); 2270 R->addRange(Range); 2271 C.emitReport(std::move(R)); 2272 } 2273 } 2274 2275 void MallocChecker::HandleMismatchedDealloc(CheckerContext &C, 2276 SourceRange Range, 2277 const Expr *DeallocExpr, 2278 const RefState *RS, SymbolRef Sym, 2279 bool OwnershipTransferred) const { 2280 2281 if (!ChecksEnabled[CK_MismatchedDeallocatorChecker]) { 2282 C.addSink(); 2283 return; 2284 } 2285 2286 if (ExplodedNode *N = C.generateErrorNode()) { 2287 if (!BT_MismatchedDealloc) 2288 BT_MismatchedDealloc.reset( 2289 new BugType(CheckNames[CK_MismatchedDeallocatorChecker], 2290 "Bad deallocator", categories::MemoryError)); 2291 2292 SmallString<100> buf; 2293 llvm::raw_svector_ostream os(buf); 2294 2295 const Expr *AllocExpr = cast<Expr>(RS->getStmt()); 2296 SmallString<20> AllocBuf; 2297 llvm::raw_svector_ostream AllocOs(AllocBuf); 2298 SmallString<20> DeallocBuf; 2299 llvm::raw_svector_ostream DeallocOs(DeallocBuf); 2300 2301 if (OwnershipTransferred) { 2302 if (printMemFnName(DeallocOs, C, DeallocExpr)) 2303 os << DeallocOs.str() << " cannot"; 2304 else 2305 os << "Cannot"; 2306 2307 os << " take ownership of memory"; 2308 2309 if (printMemFnName(AllocOs, C, AllocExpr)) 2310 os << " allocated by " << AllocOs.str(); 2311 } else { 2312 os << "Memory"; 2313 if (printMemFnName(AllocOs, C, AllocExpr)) 2314 os << " allocated by " << AllocOs.str(); 2315 2316 os << " should be deallocated by "; 2317 printExpectedDeallocName(os, RS->getAllocationFamily()); 2318 2319 if (printMemFnName(DeallocOs, C, DeallocExpr)) 2320 os << ", not " << DeallocOs.str(); 2321 } 2322 2323 auto R = std::make_unique<PathSensitiveBugReport>(*BT_MismatchedDealloc, 2324 os.str(), N); 2325 R->markInteresting(Sym); 2326 R->addRange(Range); 2327 R->addVisitor<MallocBugVisitor>(Sym); 2328 C.emitReport(std::move(R)); 2329 } 2330 } 2331 2332 void MallocChecker::HandleOffsetFree(CheckerContext &C, SVal ArgVal, 2333 SourceRange Range, const Expr *DeallocExpr, 2334 AllocationFamily Family, 2335 const Expr *AllocExpr) const { 2336 2337 if (!ChecksEnabled[CK_MallocChecker] && !ChecksEnabled[CK_NewDeleteChecker]) { 2338 C.addSink(); 2339 return; 2340 } 2341 2342 Optional<MallocChecker::CheckKind> CheckKind = getCheckIfTracked(Family); 2343 if (!CheckKind) 2344 return; 2345 2346 ExplodedNode *N = C.generateErrorNode(); 2347 if (!N) 2348 return; 2349 2350 if (!BT_OffsetFree[*CheckKind]) 2351 BT_OffsetFree[*CheckKind].reset(new BugType( 2352 CheckNames[*CheckKind], "Offset free", categories::MemoryError)); 2353 2354 SmallString<100> buf; 2355 llvm::raw_svector_ostream os(buf); 2356 SmallString<20> AllocNameBuf; 2357 llvm::raw_svector_ostream AllocNameOs(AllocNameBuf); 2358 2359 const MemRegion *MR = ArgVal.getAsRegion(); 2360 assert(MR && "Only MemRegion based symbols can have offset free errors"); 2361 2362 RegionOffset Offset = MR->getAsOffset(); 2363 assert((Offset.isValid() && 2364 !Offset.hasSymbolicOffset() && 2365 Offset.getOffset() != 0) && 2366 "Only symbols with a valid offset can have offset free errors"); 2367 2368 int offsetBytes = Offset.getOffset() / C.getASTContext().getCharWidth(); 2369 2370 os << "Argument to "; 2371 if (!printMemFnName(os, C, DeallocExpr)) 2372 os << "deallocator"; 2373 os << " is offset by " 2374 << offsetBytes 2375 << " " 2376 << ((abs(offsetBytes) > 1) ? "bytes" : "byte") 2377 << " from the start of "; 2378 if (AllocExpr && printMemFnName(AllocNameOs, C, AllocExpr)) 2379 os << "memory allocated by " << AllocNameOs.str(); 2380 else 2381 os << "allocated memory"; 2382 2383 auto R = std::make_unique<PathSensitiveBugReport>(*BT_OffsetFree[*CheckKind], 2384 os.str(), N); 2385 R->markInteresting(MR->getBaseRegion()); 2386 R->addRange(Range); 2387 C.emitReport(std::move(R)); 2388 } 2389 2390 void MallocChecker::HandleUseAfterFree(CheckerContext &C, SourceRange Range, 2391 SymbolRef Sym) const { 2392 2393 if (!ChecksEnabled[CK_MallocChecker] && !ChecksEnabled[CK_NewDeleteChecker] && 2394 !ChecksEnabled[CK_InnerPointerChecker]) { 2395 C.addSink(); 2396 return; 2397 } 2398 2399 Optional<MallocChecker::CheckKind> CheckKind = getCheckIfTracked(C, Sym); 2400 if (!CheckKind) 2401 return; 2402 2403 if (ExplodedNode *N = C.generateErrorNode()) { 2404 if (!BT_UseFree[*CheckKind]) 2405 BT_UseFree[*CheckKind].reset(new BugType( 2406 CheckNames[*CheckKind], "Use-after-free", categories::MemoryError)); 2407 2408 AllocationFamily AF = 2409 C.getState()->get<RegionState>(Sym)->getAllocationFamily(); 2410 2411 auto R = std::make_unique<PathSensitiveBugReport>( 2412 *BT_UseFree[*CheckKind], 2413 AF == AF_InnerBuffer 2414 ? "Inner pointer of container used after re/deallocation" 2415 : "Use of memory after it is freed", 2416 N); 2417 2418 R->markInteresting(Sym); 2419 R->addRange(Range); 2420 R->addVisitor<MallocBugVisitor>(Sym); 2421 2422 if (AF == AF_InnerBuffer) 2423 R->addVisitor(allocation_state::getInnerPointerBRVisitor(Sym)); 2424 2425 C.emitReport(std::move(R)); 2426 } 2427 } 2428 2429 void MallocChecker::HandleDoubleFree(CheckerContext &C, SourceRange Range, 2430 bool Released, SymbolRef Sym, 2431 SymbolRef PrevSym) const { 2432 2433 if (!ChecksEnabled[CK_MallocChecker] && !ChecksEnabled[CK_NewDeleteChecker]) { 2434 C.addSink(); 2435 return; 2436 } 2437 2438 Optional<MallocChecker::CheckKind> CheckKind = getCheckIfTracked(C, Sym); 2439 if (!CheckKind) 2440 return; 2441 2442 if (ExplodedNode *N = C.generateErrorNode()) { 2443 if (!BT_DoubleFree[*CheckKind]) 2444 BT_DoubleFree[*CheckKind].reset(new BugType( 2445 CheckNames[*CheckKind], "Double free", categories::MemoryError)); 2446 2447 auto R = std::make_unique<PathSensitiveBugReport>( 2448 *BT_DoubleFree[*CheckKind], 2449 (Released ? "Attempt to free released memory" 2450 : "Attempt to free non-owned memory"), 2451 N); 2452 R->addRange(Range); 2453 R->markInteresting(Sym); 2454 if (PrevSym) 2455 R->markInteresting(PrevSym); 2456 R->addVisitor<MallocBugVisitor>(Sym); 2457 C.emitReport(std::move(R)); 2458 } 2459 } 2460 2461 void MallocChecker::HandleDoubleDelete(CheckerContext &C, SymbolRef Sym) const { 2462 2463 if (!ChecksEnabled[CK_NewDeleteChecker]) { 2464 C.addSink(); 2465 return; 2466 } 2467 2468 Optional<MallocChecker::CheckKind> CheckKind = getCheckIfTracked(C, Sym); 2469 if (!CheckKind) 2470 return; 2471 2472 if (ExplodedNode *N = C.generateErrorNode()) { 2473 if (!BT_DoubleDelete) 2474 BT_DoubleDelete.reset(new BugType(CheckNames[CK_NewDeleteChecker], 2475 "Double delete", 2476 categories::MemoryError)); 2477 2478 auto R = std::make_unique<PathSensitiveBugReport>( 2479 *BT_DoubleDelete, "Attempt to delete released memory", N); 2480 2481 R->markInteresting(Sym); 2482 R->addVisitor<MallocBugVisitor>(Sym); 2483 C.emitReport(std::move(R)); 2484 } 2485 } 2486 2487 void MallocChecker::HandleUseZeroAlloc(CheckerContext &C, SourceRange Range, 2488 SymbolRef Sym) const { 2489 2490 if (!ChecksEnabled[CK_MallocChecker] && !ChecksEnabled[CK_NewDeleteChecker]) { 2491 C.addSink(); 2492 return; 2493 } 2494 2495 Optional<MallocChecker::CheckKind> CheckKind = getCheckIfTracked(C, Sym); 2496 2497 if (!CheckKind) 2498 return; 2499 2500 if (ExplodedNode *N = C.generateErrorNode()) { 2501 if (!BT_UseZerroAllocated[*CheckKind]) 2502 BT_UseZerroAllocated[*CheckKind].reset( 2503 new BugType(CheckNames[*CheckKind], "Use of zero allocated", 2504 categories::MemoryError)); 2505 2506 auto R = std::make_unique<PathSensitiveBugReport>( 2507 *BT_UseZerroAllocated[*CheckKind], 2508 "Use of memory allocated with size zero", N); 2509 2510 R->addRange(Range); 2511 if (Sym) { 2512 R->markInteresting(Sym); 2513 R->addVisitor<MallocBugVisitor>(Sym); 2514 } 2515 C.emitReport(std::move(R)); 2516 } 2517 } 2518 2519 void MallocChecker::HandleFunctionPtrFree(CheckerContext &C, SVal ArgVal, 2520 SourceRange Range, 2521 const Expr *FreeExpr, 2522 AllocationFamily Family) const { 2523 if (!ChecksEnabled[CK_MallocChecker]) { 2524 C.addSink(); 2525 return; 2526 } 2527 2528 Optional<MallocChecker::CheckKind> CheckKind = getCheckIfTracked(Family); 2529 if (!CheckKind) 2530 return; 2531 2532 if (ExplodedNode *N = C.generateErrorNode()) { 2533 if (!BT_BadFree[*CheckKind]) 2534 BT_BadFree[*CheckKind].reset(new BugType( 2535 CheckNames[*CheckKind], "Bad free", categories::MemoryError)); 2536 2537 SmallString<100> Buf; 2538 llvm::raw_svector_ostream Os(Buf); 2539 2540 const MemRegion *MR = ArgVal.getAsRegion(); 2541 while (const ElementRegion *ER = dyn_cast_or_null<ElementRegion>(MR)) 2542 MR = ER->getSuperRegion(); 2543 2544 Os << "Argument to "; 2545 if (!printMemFnName(Os, C, FreeExpr)) 2546 Os << "deallocator"; 2547 2548 Os << " is a function pointer"; 2549 2550 auto R = std::make_unique<PathSensitiveBugReport>(*BT_BadFree[*CheckKind], 2551 Os.str(), N); 2552 R->markInteresting(MR); 2553 R->addRange(Range); 2554 C.emitReport(std::move(R)); 2555 } 2556 } 2557 2558 ProgramStateRef 2559 MallocChecker::ReallocMemAux(CheckerContext &C, const CallEvent &Call, 2560 bool ShouldFreeOnFail, ProgramStateRef State, 2561 AllocationFamily Family, bool SuffixWithN) const { 2562 if (!State) 2563 return nullptr; 2564 2565 const CallExpr *CE = cast<CallExpr>(Call.getOriginExpr()); 2566 2567 if (SuffixWithN && CE->getNumArgs() < 3) 2568 return nullptr; 2569 else if (CE->getNumArgs() < 2) 2570 return nullptr; 2571 2572 const Expr *arg0Expr = CE->getArg(0); 2573 SVal Arg0Val = C.getSVal(arg0Expr); 2574 if (!isa<DefinedOrUnknownSVal>(Arg0Val)) 2575 return nullptr; 2576 DefinedOrUnknownSVal arg0Val = Arg0Val.castAs<DefinedOrUnknownSVal>(); 2577 2578 SValBuilder &svalBuilder = C.getSValBuilder(); 2579 2580 DefinedOrUnknownSVal PtrEQ = svalBuilder.evalEQ( 2581 State, arg0Val, svalBuilder.makeNullWithType(arg0Expr->getType())); 2582 2583 // Get the size argument. 2584 const Expr *Arg1 = CE->getArg(1); 2585 2586 // Get the value of the size argument. 2587 SVal TotalSize = C.getSVal(Arg1); 2588 if (SuffixWithN) 2589 TotalSize = evalMulForBufferSize(C, Arg1, CE->getArg(2)); 2590 if (!isa<DefinedOrUnknownSVal>(TotalSize)) 2591 return nullptr; 2592 2593 // Compare the size argument to 0. 2594 DefinedOrUnknownSVal SizeZero = 2595 svalBuilder.evalEQ(State, TotalSize.castAs<DefinedOrUnknownSVal>(), 2596 svalBuilder.makeIntValWithWidth( 2597 svalBuilder.getContext().getSizeType(), 0)); 2598 2599 ProgramStateRef StatePtrIsNull, StatePtrNotNull; 2600 std::tie(StatePtrIsNull, StatePtrNotNull) = State->assume(PtrEQ); 2601 ProgramStateRef StateSizeIsZero, StateSizeNotZero; 2602 std::tie(StateSizeIsZero, StateSizeNotZero) = State->assume(SizeZero); 2603 // We only assume exceptional states if they are definitely true; if the 2604 // state is under-constrained, assume regular realloc behavior. 2605 bool PrtIsNull = StatePtrIsNull && !StatePtrNotNull; 2606 bool SizeIsZero = StateSizeIsZero && !StateSizeNotZero; 2607 2608 // If the ptr is NULL and the size is not 0, the call is equivalent to 2609 // malloc(size). 2610 if (PrtIsNull && !SizeIsZero) { 2611 ProgramStateRef stateMalloc = MallocMemAux( 2612 C, Call, TotalSize, UndefinedVal(), StatePtrIsNull, Family); 2613 return stateMalloc; 2614 } 2615 2616 if (PrtIsNull && SizeIsZero) 2617 return State; 2618 2619 assert(!PrtIsNull); 2620 2621 bool IsKnownToBeAllocated = false; 2622 2623 // If the size is 0, free the memory. 2624 if (SizeIsZero) 2625 // The semantics of the return value are: 2626 // If size was equal to 0, either NULL or a pointer suitable to be passed 2627 // to free() is returned. We just free the input pointer and do not add 2628 // any constrains on the output pointer. 2629 if (ProgramStateRef stateFree = FreeMemAux( 2630 C, Call, StateSizeIsZero, 0, false, IsKnownToBeAllocated, Family)) 2631 return stateFree; 2632 2633 // Default behavior. 2634 if (ProgramStateRef stateFree = 2635 FreeMemAux(C, Call, State, 0, false, IsKnownToBeAllocated, Family)) { 2636 2637 ProgramStateRef stateRealloc = 2638 MallocMemAux(C, Call, TotalSize, UnknownVal(), stateFree, Family); 2639 if (!stateRealloc) 2640 return nullptr; 2641 2642 OwnershipAfterReallocKind Kind = OAR_ToBeFreedAfterFailure; 2643 if (ShouldFreeOnFail) 2644 Kind = OAR_FreeOnFailure; 2645 else if (!IsKnownToBeAllocated) 2646 Kind = OAR_DoNotTrackAfterFailure; 2647 2648 // Get the from and to pointer symbols as in toPtr = realloc(fromPtr, size). 2649 SymbolRef FromPtr = arg0Val.getLocSymbolInBase(); 2650 SVal RetVal = C.getSVal(CE); 2651 SymbolRef ToPtr = RetVal.getAsSymbol(); 2652 assert(FromPtr && ToPtr && 2653 "By this point, FreeMemAux and MallocMemAux should have checked " 2654 "whether the argument or the return value is symbolic!"); 2655 2656 // Record the info about the reallocated symbol so that we could properly 2657 // process failed reallocation. 2658 stateRealloc = stateRealloc->set<ReallocPairs>(ToPtr, 2659 ReallocPair(FromPtr, Kind)); 2660 // The reallocated symbol should stay alive for as long as the new symbol. 2661 C.getSymbolManager().addSymbolDependency(ToPtr, FromPtr); 2662 return stateRealloc; 2663 } 2664 return nullptr; 2665 } 2666 2667 ProgramStateRef MallocChecker::CallocMem(CheckerContext &C, 2668 const CallEvent &Call, 2669 ProgramStateRef State) { 2670 if (!State) 2671 return nullptr; 2672 2673 if (Call.getNumArgs() < 2) 2674 return nullptr; 2675 2676 SValBuilder &svalBuilder = C.getSValBuilder(); 2677 SVal zeroVal = svalBuilder.makeZeroVal(svalBuilder.getContext().CharTy); 2678 SVal TotalSize = 2679 evalMulForBufferSize(C, Call.getArgExpr(0), Call.getArgExpr(1)); 2680 2681 return MallocMemAux(C, Call, TotalSize, zeroVal, State, AF_Malloc); 2682 } 2683 2684 MallocChecker::LeakInfo MallocChecker::getAllocationSite(const ExplodedNode *N, 2685 SymbolRef Sym, 2686 CheckerContext &C) { 2687 const LocationContext *LeakContext = N->getLocationContext(); 2688 // Walk the ExplodedGraph backwards and find the first node that referred to 2689 // the tracked symbol. 2690 const ExplodedNode *AllocNode = N; 2691 const MemRegion *ReferenceRegion = nullptr; 2692 2693 while (N) { 2694 ProgramStateRef State = N->getState(); 2695 if (!State->get<RegionState>(Sym)) 2696 break; 2697 2698 // Find the most recent expression bound to the symbol in the current 2699 // context. 2700 if (!ReferenceRegion) { 2701 if (const MemRegion *MR = C.getLocationRegionIfPostStore(N)) { 2702 SVal Val = State->getSVal(MR); 2703 if (Val.getAsLocSymbol() == Sym) { 2704 const VarRegion *VR = MR->getBaseRegion()->getAs<VarRegion>(); 2705 // Do not show local variables belonging to a function other than 2706 // where the error is reported. 2707 if (!VR || (VR->getStackFrame() == LeakContext->getStackFrame())) 2708 ReferenceRegion = MR; 2709 } 2710 } 2711 } 2712 2713 // Allocation node, is the last node in the current or parent context in 2714 // which the symbol was tracked. 2715 const LocationContext *NContext = N->getLocationContext(); 2716 if (NContext == LeakContext || 2717 NContext->isParentOf(LeakContext)) 2718 AllocNode = N; 2719 N = N->pred_empty() ? nullptr : *(N->pred_begin()); 2720 } 2721 2722 return LeakInfo(AllocNode, ReferenceRegion); 2723 } 2724 2725 void MallocChecker::HandleLeak(SymbolRef Sym, ExplodedNode *N, 2726 CheckerContext &C) const { 2727 2728 if (!ChecksEnabled[CK_MallocChecker] && 2729 !ChecksEnabled[CK_NewDeleteLeaksChecker]) 2730 return; 2731 2732 const RefState *RS = C.getState()->get<RegionState>(Sym); 2733 assert(RS && "cannot leak an untracked symbol"); 2734 AllocationFamily Family = RS->getAllocationFamily(); 2735 2736 if (Family == AF_Alloca) 2737 return; 2738 2739 Optional<MallocChecker::CheckKind> 2740 CheckKind = getCheckIfTracked(Family, true); 2741 2742 if (!CheckKind) 2743 return; 2744 2745 assert(N); 2746 if (!BT_Leak[*CheckKind]) { 2747 // Leaks should not be reported if they are post-dominated by a sink: 2748 // (1) Sinks are higher importance bugs. 2749 // (2) NoReturnFunctionChecker uses sink nodes to represent paths ending 2750 // with __noreturn functions such as assert() or exit(). We choose not 2751 // to report leaks on such paths. 2752 BT_Leak[*CheckKind].reset(new BugType(CheckNames[*CheckKind], "Memory leak", 2753 categories::MemoryError, 2754 /*SuppressOnSink=*/true)); 2755 } 2756 2757 // Most bug reports are cached at the location where they occurred. 2758 // With leaks, we want to unique them by the location where they were 2759 // allocated, and only report a single path. 2760 PathDiagnosticLocation LocUsedForUniqueing; 2761 const ExplodedNode *AllocNode = nullptr; 2762 const MemRegion *Region = nullptr; 2763 std::tie(AllocNode, Region) = getAllocationSite(N, Sym, C); 2764 2765 const Stmt *AllocationStmt = AllocNode->getStmtForDiagnostics(); 2766 if (AllocationStmt) 2767 LocUsedForUniqueing = PathDiagnosticLocation::createBegin(AllocationStmt, 2768 C.getSourceManager(), 2769 AllocNode->getLocationContext()); 2770 2771 SmallString<200> buf; 2772 llvm::raw_svector_ostream os(buf); 2773 if (Region && Region->canPrintPretty()) { 2774 os << "Potential leak of memory pointed to by "; 2775 Region->printPretty(os); 2776 } else { 2777 os << "Potential memory leak"; 2778 } 2779 2780 auto R = std::make_unique<PathSensitiveBugReport>( 2781 *BT_Leak[*CheckKind], os.str(), N, LocUsedForUniqueing, 2782 AllocNode->getLocationContext()->getDecl()); 2783 R->markInteresting(Sym); 2784 R->addVisitor<MallocBugVisitor>(Sym, true); 2785 if (ShouldRegisterNoOwnershipChangeVisitor) 2786 R->addVisitor<NoOwnershipChangeVisitor>(Sym, this); 2787 C.emitReport(std::move(R)); 2788 } 2789 2790 void MallocChecker::checkDeadSymbols(SymbolReaper &SymReaper, 2791 CheckerContext &C) const 2792 { 2793 ProgramStateRef state = C.getState(); 2794 RegionStateTy OldRS = state->get<RegionState>(); 2795 RegionStateTy::Factory &F = state->get_context<RegionState>(); 2796 2797 RegionStateTy RS = OldRS; 2798 SmallVector<SymbolRef, 2> Errors; 2799 for (RegionStateTy::iterator I = RS.begin(), E = RS.end(); I != E; ++I) { 2800 if (SymReaper.isDead(I->first)) { 2801 if (I->second.isAllocated() || I->second.isAllocatedOfSizeZero()) 2802 Errors.push_back(I->first); 2803 // Remove the dead symbol from the map. 2804 RS = F.remove(RS, I->first); 2805 } 2806 } 2807 2808 if (RS == OldRS) { 2809 // We shouldn't have touched other maps yet. 2810 assert(state->get<ReallocPairs>() == 2811 C.getState()->get<ReallocPairs>()); 2812 assert(state->get<FreeReturnValue>() == 2813 C.getState()->get<FreeReturnValue>()); 2814 return; 2815 } 2816 2817 // Cleanup the Realloc Pairs Map. 2818 ReallocPairsTy RP = state->get<ReallocPairs>(); 2819 for (ReallocPairsTy::iterator I = RP.begin(), E = RP.end(); I != E; ++I) { 2820 if (SymReaper.isDead(I->first) || 2821 SymReaper.isDead(I->second.ReallocatedSym)) { 2822 state = state->remove<ReallocPairs>(I->first); 2823 } 2824 } 2825 2826 // Cleanup the FreeReturnValue Map. 2827 FreeReturnValueTy FR = state->get<FreeReturnValue>(); 2828 for (FreeReturnValueTy::iterator I = FR.begin(), E = FR.end(); I != E; ++I) { 2829 if (SymReaper.isDead(I->first) || 2830 SymReaper.isDead(I->second)) { 2831 state = state->remove<FreeReturnValue>(I->first); 2832 } 2833 } 2834 2835 // Generate leak node. 2836 ExplodedNode *N = C.getPredecessor(); 2837 if (!Errors.empty()) { 2838 static CheckerProgramPointTag Tag("MallocChecker", "DeadSymbolsLeak"); 2839 N = C.generateNonFatalErrorNode(C.getState(), &Tag); 2840 if (N) { 2841 for (SmallVectorImpl<SymbolRef>::iterator 2842 I = Errors.begin(), E = Errors.end(); I != E; ++I) { 2843 HandleLeak(*I, N, C); 2844 } 2845 } 2846 } 2847 2848 C.addTransition(state->set<RegionState>(RS), N); 2849 } 2850 2851 void MallocChecker::checkPreCall(const CallEvent &Call, 2852 CheckerContext &C) const { 2853 2854 if (const auto *DC = dyn_cast<CXXDeallocatorCall>(&Call)) { 2855 const CXXDeleteExpr *DE = DC->getOriginExpr(); 2856 2857 if (!ChecksEnabled[CK_NewDeleteChecker]) 2858 if (SymbolRef Sym = C.getSVal(DE->getArgument()).getAsSymbol()) 2859 checkUseAfterFree(Sym, C, DE->getArgument()); 2860 2861 if (!isStandardNewDelete(DC->getDecl())) 2862 return; 2863 2864 ProgramStateRef State = C.getState(); 2865 bool IsKnownToBeAllocated; 2866 State = FreeMemAux(C, DE->getArgument(), Call, State, 2867 /*Hold*/ false, IsKnownToBeAllocated, 2868 (DE->isArrayForm() ? AF_CXXNewArray : AF_CXXNew)); 2869 2870 C.addTransition(State); 2871 return; 2872 } 2873 2874 if (const auto *DC = dyn_cast<CXXDestructorCall>(&Call)) { 2875 SymbolRef Sym = DC->getCXXThisVal().getAsSymbol(); 2876 if (!Sym || checkDoubleDelete(Sym, C)) 2877 return; 2878 } 2879 2880 // We will check for double free in the post visit. 2881 if (const AnyFunctionCall *FC = dyn_cast<AnyFunctionCall>(&Call)) { 2882 const FunctionDecl *FD = FC->getDecl(); 2883 if (!FD) 2884 return; 2885 2886 if (ChecksEnabled[CK_MallocChecker] && isFreeingCall(Call)) 2887 return; 2888 } 2889 2890 // Check if the callee of a method is deleted. 2891 if (const CXXInstanceCall *CC = dyn_cast<CXXInstanceCall>(&Call)) { 2892 SymbolRef Sym = CC->getCXXThisVal().getAsSymbol(); 2893 if (!Sym || checkUseAfterFree(Sym, C, CC->getCXXThisExpr())) 2894 return; 2895 } 2896 2897 // Check arguments for being used after free. 2898 for (unsigned I = 0, E = Call.getNumArgs(); I != E; ++I) { 2899 SVal ArgSVal = Call.getArgSVal(I); 2900 if (isa<Loc>(ArgSVal)) { 2901 SymbolRef Sym = ArgSVal.getAsSymbol(); 2902 if (!Sym) 2903 continue; 2904 if (checkUseAfterFree(Sym, C, Call.getArgExpr(I))) 2905 return; 2906 } 2907 } 2908 } 2909 2910 void MallocChecker::checkPreStmt(const ReturnStmt *S, 2911 CheckerContext &C) const { 2912 checkEscapeOnReturn(S, C); 2913 } 2914 2915 // In the CFG, automatic destructors come after the return statement. 2916 // This callback checks for returning memory that is freed by automatic 2917 // destructors, as those cannot be reached in checkPreStmt(). 2918 void MallocChecker::checkEndFunction(const ReturnStmt *S, 2919 CheckerContext &C) const { 2920 checkEscapeOnReturn(S, C); 2921 } 2922 2923 void MallocChecker::checkEscapeOnReturn(const ReturnStmt *S, 2924 CheckerContext &C) const { 2925 if (!S) 2926 return; 2927 2928 const Expr *E = S->getRetValue(); 2929 if (!E) 2930 return; 2931 2932 // Check if we are returning a symbol. 2933 ProgramStateRef State = C.getState(); 2934 SVal RetVal = C.getSVal(E); 2935 SymbolRef Sym = RetVal.getAsSymbol(); 2936 if (!Sym) 2937 // If we are returning a field of the allocated struct or an array element, 2938 // the callee could still free the memory. 2939 // TODO: This logic should be a part of generic symbol escape callback. 2940 if (const MemRegion *MR = RetVal.getAsRegion()) 2941 if (isa<FieldRegion, ElementRegion>(MR)) 2942 if (const SymbolicRegion *BMR = 2943 dyn_cast<SymbolicRegion>(MR->getBaseRegion())) 2944 Sym = BMR->getSymbol(); 2945 2946 // Check if we are returning freed memory. 2947 if (Sym) 2948 checkUseAfterFree(Sym, C, E); 2949 } 2950 2951 // TODO: Blocks should be either inlined or should call invalidate regions 2952 // upon invocation. After that's in place, special casing here will not be 2953 // needed. 2954 void MallocChecker::checkPostStmt(const BlockExpr *BE, 2955 CheckerContext &C) const { 2956 2957 // Scan the BlockDecRefExprs for any object the retain count checker 2958 // may be tracking. 2959 if (!BE->getBlockDecl()->hasCaptures()) 2960 return; 2961 2962 ProgramStateRef state = C.getState(); 2963 const BlockDataRegion *R = 2964 cast<BlockDataRegion>(C.getSVal(BE).getAsRegion()); 2965 2966 BlockDataRegion::referenced_vars_iterator I = R->referenced_vars_begin(), 2967 E = R->referenced_vars_end(); 2968 2969 if (I == E) 2970 return; 2971 2972 SmallVector<const MemRegion*, 10> Regions; 2973 const LocationContext *LC = C.getLocationContext(); 2974 MemRegionManager &MemMgr = C.getSValBuilder().getRegionManager(); 2975 2976 for ( ; I != E; ++I) { 2977 const VarRegion *VR = I.getCapturedRegion(); 2978 if (VR->getSuperRegion() == R) { 2979 VR = MemMgr.getVarRegion(VR->getDecl(), LC); 2980 } 2981 Regions.push_back(VR); 2982 } 2983 2984 state = 2985 state->scanReachableSymbols<StopTrackingCallback>(Regions).getState(); 2986 C.addTransition(state); 2987 } 2988 2989 static bool isReleased(SymbolRef Sym, CheckerContext &C) { 2990 assert(Sym); 2991 const RefState *RS = C.getState()->get<RegionState>(Sym); 2992 return (RS && RS->isReleased()); 2993 } 2994 2995 bool MallocChecker::suppressDeallocationsInSuspiciousContexts( 2996 const CallEvent &Call, CheckerContext &C) const { 2997 if (Call.getNumArgs() == 0) 2998 return false; 2999 3000 StringRef FunctionStr = ""; 3001 if (const auto *FD = dyn_cast<FunctionDecl>(C.getStackFrame()->getDecl())) 3002 if (const Stmt *Body = FD->getBody()) 3003 if (Body->getBeginLoc().isValid()) 3004 FunctionStr = 3005 Lexer::getSourceText(CharSourceRange::getTokenRange( 3006 {FD->getBeginLoc(), Body->getBeginLoc()}), 3007 C.getSourceManager(), C.getLangOpts()); 3008 3009 // We do not model the Integer Set Library's retain-count based allocation. 3010 if (!FunctionStr.contains("__isl_")) 3011 return false; 3012 3013 ProgramStateRef State = C.getState(); 3014 3015 for (const Expr *Arg : cast<CallExpr>(Call.getOriginExpr())->arguments()) 3016 if (SymbolRef Sym = C.getSVal(Arg).getAsSymbol()) 3017 if (const RefState *RS = State->get<RegionState>(Sym)) 3018 State = State->set<RegionState>(Sym, RefState::getEscaped(RS)); 3019 3020 C.addTransition(State); 3021 return true; 3022 } 3023 3024 bool MallocChecker::checkUseAfterFree(SymbolRef Sym, CheckerContext &C, 3025 const Stmt *S) const { 3026 3027 if (isReleased(Sym, C)) { 3028 HandleUseAfterFree(C, S->getSourceRange(), Sym); 3029 return true; 3030 } 3031 3032 return false; 3033 } 3034 3035 void MallocChecker::checkUseZeroAllocated(SymbolRef Sym, CheckerContext &C, 3036 const Stmt *S) const { 3037 assert(Sym); 3038 3039 if (const RefState *RS = C.getState()->get<RegionState>(Sym)) { 3040 if (RS->isAllocatedOfSizeZero()) 3041 HandleUseZeroAlloc(C, RS->getStmt()->getSourceRange(), Sym); 3042 } 3043 else if (C.getState()->contains<ReallocSizeZeroSymbols>(Sym)) { 3044 HandleUseZeroAlloc(C, S->getSourceRange(), Sym); 3045 } 3046 } 3047 3048 bool MallocChecker::checkDoubleDelete(SymbolRef Sym, CheckerContext &C) const { 3049 3050 if (isReleased(Sym, C)) { 3051 HandleDoubleDelete(C, Sym); 3052 return true; 3053 } 3054 return false; 3055 } 3056 3057 // Check if the location is a freed symbolic region. 3058 void MallocChecker::checkLocation(SVal l, bool isLoad, const Stmt *S, 3059 CheckerContext &C) const { 3060 SymbolRef Sym = l.getLocSymbolInBase(); 3061 if (Sym) { 3062 checkUseAfterFree(Sym, C, S); 3063 checkUseZeroAllocated(Sym, C, S); 3064 } 3065 } 3066 3067 // If a symbolic region is assumed to NULL (or another constant), stop tracking 3068 // it - assuming that allocation failed on this path. 3069 ProgramStateRef MallocChecker::evalAssume(ProgramStateRef state, 3070 SVal Cond, 3071 bool Assumption) const { 3072 RegionStateTy RS = state->get<RegionState>(); 3073 for (RegionStateTy::iterator I = RS.begin(), E = RS.end(); I != E; ++I) { 3074 // If the symbol is assumed to be NULL, remove it from consideration. 3075 ConstraintManager &CMgr = state->getConstraintManager(); 3076 ConditionTruthVal AllocFailed = CMgr.isNull(state, I.getKey()); 3077 if (AllocFailed.isConstrainedTrue()) 3078 state = state->remove<RegionState>(I.getKey()); 3079 } 3080 3081 // Realloc returns 0 when reallocation fails, which means that we should 3082 // restore the state of the pointer being reallocated. 3083 ReallocPairsTy RP = state->get<ReallocPairs>(); 3084 for (ReallocPairsTy::iterator I = RP.begin(), E = RP.end(); I != E; ++I) { 3085 // If the symbol is assumed to be NULL, remove it from consideration. 3086 ConstraintManager &CMgr = state->getConstraintManager(); 3087 ConditionTruthVal AllocFailed = CMgr.isNull(state, I.getKey()); 3088 if (!AllocFailed.isConstrainedTrue()) 3089 continue; 3090 3091 SymbolRef ReallocSym = I.getData().ReallocatedSym; 3092 if (const RefState *RS = state->get<RegionState>(ReallocSym)) { 3093 if (RS->isReleased()) { 3094 switch (I.getData().Kind) { 3095 case OAR_ToBeFreedAfterFailure: 3096 state = state->set<RegionState>(ReallocSym, 3097 RefState::getAllocated(RS->getAllocationFamily(), RS->getStmt())); 3098 break; 3099 case OAR_DoNotTrackAfterFailure: 3100 state = state->remove<RegionState>(ReallocSym); 3101 break; 3102 default: 3103 assert(I.getData().Kind == OAR_FreeOnFailure); 3104 } 3105 } 3106 } 3107 state = state->remove<ReallocPairs>(I.getKey()); 3108 } 3109 3110 return state; 3111 } 3112 3113 bool MallocChecker::mayFreeAnyEscapedMemoryOrIsModeledExplicitly( 3114 const CallEvent *Call, 3115 ProgramStateRef State, 3116 SymbolRef &EscapingSymbol) const { 3117 assert(Call); 3118 EscapingSymbol = nullptr; 3119 3120 // For now, assume that any C++ or block call can free memory. 3121 // TODO: If we want to be more optimistic here, we'll need to make sure that 3122 // regions escape to C++ containers. They seem to do that even now, but for 3123 // mysterious reasons. 3124 if (!isa<SimpleFunctionCall, ObjCMethodCall>(Call)) 3125 return true; 3126 3127 // Check Objective-C messages by selector name. 3128 if (const ObjCMethodCall *Msg = dyn_cast<ObjCMethodCall>(Call)) { 3129 // If it's not a framework call, or if it takes a callback, assume it 3130 // can free memory. 3131 if (!Call->isInSystemHeader() || Call->argumentsMayEscape()) 3132 return true; 3133 3134 // If it's a method we know about, handle it explicitly post-call. 3135 // This should happen before the "freeWhenDone" check below. 3136 if (isKnownDeallocObjCMethodName(*Msg)) 3137 return false; 3138 3139 // If there's a "freeWhenDone" parameter, but the method isn't one we know 3140 // about, we can't be sure that the object will use free() to deallocate the 3141 // memory, so we can't model it explicitly. The best we can do is use it to 3142 // decide whether the pointer escapes. 3143 if (std::optional<bool> FreeWhenDone = getFreeWhenDoneArg(*Msg)) 3144 return *FreeWhenDone; 3145 3146 // If the first selector piece ends with "NoCopy", and there is no 3147 // "freeWhenDone" parameter set to zero, we know ownership is being 3148 // transferred. Again, though, we can't be sure that the object will use 3149 // free() to deallocate the memory, so we can't model it explicitly. 3150 StringRef FirstSlot = Msg->getSelector().getNameForSlot(0); 3151 if (FirstSlot.endswith("NoCopy")) 3152 return true; 3153 3154 // If the first selector starts with addPointer, insertPointer, 3155 // or replacePointer, assume we are dealing with NSPointerArray or similar. 3156 // This is similar to C++ containers (vector); we still might want to check 3157 // that the pointers get freed by following the container itself. 3158 if (FirstSlot.startswith("addPointer") || 3159 FirstSlot.startswith("insertPointer") || 3160 FirstSlot.startswith("replacePointer") || 3161 FirstSlot.equals("valueWithPointer")) { 3162 return true; 3163 } 3164 3165 // We should escape receiver on call to 'init'. This is especially relevant 3166 // to the receiver, as the corresponding symbol is usually not referenced 3167 // after the call. 3168 if (Msg->getMethodFamily() == OMF_init) { 3169 EscapingSymbol = Msg->getReceiverSVal().getAsSymbol(); 3170 return true; 3171 } 3172 3173 // Otherwise, assume that the method does not free memory. 3174 // Most framework methods do not free memory. 3175 return false; 3176 } 3177 3178 // At this point the only thing left to handle is straight function calls. 3179 const FunctionDecl *FD = cast<SimpleFunctionCall>(Call)->getDecl(); 3180 if (!FD) 3181 return true; 3182 3183 // If it's one of the allocation functions we can reason about, we model 3184 // its behavior explicitly. 3185 if (isMemCall(*Call)) 3186 return false; 3187 3188 // If it's not a system call, assume it frees memory. 3189 if (!Call->isInSystemHeader()) 3190 return true; 3191 3192 // White list the system functions whose arguments escape. 3193 const IdentifierInfo *II = FD->getIdentifier(); 3194 if (!II) 3195 return true; 3196 StringRef FName = II->getName(); 3197 3198 // White list the 'XXXNoCopy' CoreFoundation functions. 3199 // We specifically check these before 3200 if (FName.endswith("NoCopy")) { 3201 // Look for the deallocator argument. We know that the memory ownership 3202 // is not transferred only if the deallocator argument is 3203 // 'kCFAllocatorNull'. 3204 for (unsigned i = 1; i < Call->getNumArgs(); ++i) { 3205 const Expr *ArgE = Call->getArgExpr(i)->IgnoreParenCasts(); 3206 if (const DeclRefExpr *DE = dyn_cast<DeclRefExpr>(ArgE)) { 3207 StringRef DeallocatorName = DE->getFoundDecl()->getName(); 3208 if (DeallocatorName == "kCFAllocatorNull") 3209 return false; 3210 } 3211 } 3212 return true; 3213 } 3214 3215 // Associating streams with malloced buffers. The pointer can escape if 3216 // 'closefn' is specified (and if that function does free memory), 3217 // but it will not if closefn is not specified. 3218 // Currently, we do not inspect the 'closefn' function (PR12101). 3219 if (FName == "funopen") 3220 if (Call->getNumArgs() >= 4 && Call->getArgSVal(4).isConstant(0)) 3221 return false; 3222 3223 // Do not warn on pointers passed to 'setbuf' when used with std streams, 3224 // these leaks might be intentional when setting the buffer for stdio. 3225 // http://stackoverflow.com/questions/2671151/who-frees-setvbuf-buffer 3226 if (FName == "setbuf" || FName =="setbuffer" || 3227 FName == "setlinebuf" || FName == "setvbuf") { 3228 if (Call->getNumArgs() >= 1) { 3229 const Expr *ArgE = Call->getArgExpr(0)->IgnoreParenCasts(); 3230 if (const DeclRefExpr *ArgDRE = dyn_cast<DeclRefExpr>(ArgE)) 3231 if (const VarDecl *D = dyn_cast<VarDecl>(ArgDRE->getDecl())) 3232 if (D->getCanonicalDecl()->getName().contains("std")) 3233 return true; 3234 } 3235 } 3236 3237 // A bunch of other functions which either take ownership of a pointer or 3238 // wrap the result up in a struct or object, meaning it can be freed later. 3239 // (See RetainCountChecker.) Not all the parameters here are invalidated, 3240 // but the Malloc checker cannot differentiate between them. The right way 3241 // of doing this would be to implement a pointer escapes callback. 3242 if (FName == "CGBitmapContextCreate" || 3243 FName == "CGBitmapContextCreateWithData" || 3244 FName == "CVPixelBufferCreateWithBytes" || 3245 FName == "CVPixelBufferCreateWithPlanarBytes" || 3246 FName == "OSAtomicEnqueue") { 3247 return true; 3248 } 3249 3250 if (FName == "postEvent" && 3251 FD->getQualifiedNameAsString() == "QCoreApplication::postEvent") { 3252 return true; 3253 } 3254 3255 if (FName == "connectImpl" && 3256 FD->getQualifiedNameAsString() == "QObject::connectImpl") { 3257 return true; 3258 } 3259 3260 // Handle cases where we know a buffer's /address/ can escape. 3261 // Note that the above checks handle some special cases where we know that 3262 // even though the address escapes, it's still our responsibility to free the 3263 // buffer. 3264 if (Call->argumentsMayEscape()) 3265 return true; 3266 3267 // Otherwise, assume that the function does not free memory. 3268 // Most system calls do not free the memory. 3269 return false; 3270 } 3271 3272 ProgramStateRef MallocChecker::checkPointerEscape(ProgramStateRef State, 3273 const InvalidatedSymbols &Escaped, 3274 const CallEvent *Call, 3275 PointerEscapeKind Kind) const { 3276 return checkPointerEscapeAux(State, Escaped, Call, Kind, 3277 /*IsConstPointerEscape*/ false); 3278 } 3279 3280 ProgramStateRef MallocChecker::checkConstPointerEscape(ProgramStateRef State, 3281 const InvalidatedSymbols &Escaped, 3282 const CallEvent *Call, 3283 PointerEscapeKind Kind) const { 3284 // If a const pointer escapes, it may not be freed(), but it could be deleted. 3285 return checkPointerEscapeAux(State, Escaped, Call, Kind, 3286 /*IsConstPointerEscape*/ true); 3287 } 3288 3289 static bool checkIfNewOrNewArrayFamily(const RefState *RS) { 3290 return (RS->getAllocationFamily() == AF_CXXNewArray || 3291 RS->getAllocationFamily() == AF_CXXNew); 3292 } 3293 3294 ProgramStateRef MallocChecker::checkPointerEscapeAux( 3295 ProgramStateRef State, const InvalidatedSymbols &Escaped, 3296 const CallEvent *Call, PointerEscapeKind Kind, 3297 bool IsConstPointerEscape) const { 3298 // If we know that the call does not free memory, or we want to process the 3299 // call later, keep tracking the top level arguments. 3300 SymbolRef EscapingSymbol = nullptr; 3301 if (Kind == PSK_DirectEscapeOnCall && 3302 !mayFreeAnyEscapedMemoryOrIsModeledExplicitly(Call, State, 3303 EscapingSymbol) && 3304 !EscapingSymbol) { 3305 return State; 3306 } 3307 3308 for (InvalidatedSymbols::const_iterator I = Escaped.begin(), 3309 E = Escaped.end(); 3310 I != E; ++I) { 3311 SymbolRef sym = *I; 3312 3313 if (EscapingSymbol && EscapingSymbol != sym) 3314 continue; 3315 3316 if (const RefState *RS = State->get<RegionState>(sym)) 3317 if (RS->isAllocated() || RS->isAllocatedOfSizeZero()) 3318 if (!IsConstPointerEscape || checkIfNewOrNewArrayFamily(RS)) 3319 State = State->set<RegionState>(sym, RefState::getEscaped(RS)); 3320 } 3321 return State; 3322 } 3323 3324 bool MallocChecker::isArgZERO_SIZE_PTR(ProgramStateRef State, CheckerContext &C, 3325 SVal ArgVal) const { 3326 if (!KernelZeroSizePtrValue) 3327 KernelZeroSizePtrValue = 3328 tryExpandAsInteger("ZERO_SIZE_PTR", C.getPreprocessor()); 3329 3330 const llvm::APSInt *ArgValKnown = 3331 C.getSValBuilder().getKnownValue(State, ArgVal); 3332 return ArgValKnown && *KernelZeroSizePtrValue && 3333 ArgValKnown->getSExtValue() == **KernelZeroSizePtrValue; 3334 } 3335 3336 static SymbolRef findFailedReallocSymbol(ProgramStateRef currState, 3337 ProgramStateRef prevState) { 3338 ReallocPairsTy currMap = currState->get<ReallocPairs>(); 3339 ReallocPairsTy prevMap = prevState->get<ReallocPairs>(); 3340 3341 for (const ReallocPairsTy::value_type &Pair : prevMap) { 3342 SymbolRef sym = Pair.first; 3343 if (!currMap.lookup(sym)) 3344 return sym; 3345 } 3346 3347 return nullptr; 3348 } 3349 3350 static bool isReferenceCountingPointerDestructor(const CXXDestructorDecl *DD) { 3351 if (const IdentifierInfo *II = DD->getParent()->getIdentifier()) { 3352 StringRef N = II->getName(); 3353 if (N.contains_insensitive("ptr") || N.contains_insensitive("pointer")) { 3354 if (N.contains_insensitive("ref") || N.contains_insensitive("cnt") || 3355 N.contains_insensitive("intrusive") || 3356 N.contains_insensitive("shared")) { 3357 return true; 3358 } 3359 } 3360 } 3361 return false; 3362 } 3363 3364 PathDiagnosticPieceRef MallocBugVisitor::VisitNode(const ExplodedNode *N, 3365 BugReporterContext &BRC, 3366 PathSensitiveBugReport &BR) { 3367 ProgramStateRef state = N->getState(); 3368 ProgramStateRef statePrev = N->getFirstPred()->getState(); 3369 3370 const RefState *RSCurr = state->get<RegionState>(Sym); 3371 const RefState *RSPrev = statePrev->get<RegionState>(Sym); 3372 3373 const Stmt *S = N->getStmtForDiagnostics(); 3374 // When dealing with containers, we sometimes want to give a note 3375 // even if the statement is missing. 3376 if (!S && (!RSCurr || RSCurr->getAllocationFamily() != AF_InnerBuffer)) 3377 return nullptr; 3378 3379 const LocationContext *CurrentLC = N->getLocationContext(); 3380 3381 // If we find an atomic fetch_add or fetch_sub within the destructor in which 3382 // the pointer was released (before the release), this is likely a destructor 3383 // of a shared pointer. 3384 // Because we don't model atomics, and also because we don't know that the 3385 // original reference count is positive, we should not report use-after-frees 3386 // on objects deleted in such destructors. This can probably be improved 3387 // through better shared pointer modeling. 3388 if (ReleaseDestructorLC) { 3389 if (const auto *AE = dyn_cast<AtomicExpr>(S)) { 3390 AtomicExpr::AtomicOp Op = AE->getOp(); 3391 if (Op == AtomicExpr::AO__c11_atomic_fetch_add || 3392 Op == AtomicExpr::AO__c11_atomic_fetch_sub) { 3393 if (ReleaseDestructorLC == CurrentLC || 3394 ReleaseDestructorLC->isParentOf(CurrentLC)) { 3395 BR.markInvalid(getTag(), S); 3396 } 3397 } 3398 } 3399 } 3400 3401 // FIXME: We will eventually need to handle non-statement-based events 3402 // (__attribute__((cleanup))). 3403 3404 // Find out if this is an interesting point and what is the kind. 3405 StringRef Msg; 3406 std::unique_ptr<StackHintGeneratorForSymbol> StackHint = nullptr; 3407 SmallString<256> Buf; 3408 llvm::raw_svector_ostream OS(Buf); 3409 3410 if (Mode == Normal) { 3411 if (isAllocated(RSCurr, RSPrev, S)) { 3412 Msg = "Memory is allocated"; 3413 StackHint = std::make_unique<StackHintGeneratorForSymbol>( 3414 Sym, "Returned allocated memory"); 3415 } else if (isReleased(RSCurr, RSPrev, S)) { 3416 const auto Family = RSCurr->getAllocationFamily(); 3417 switch (Family) { 3418 case AF_Alloca: 3419 case AF_Malloc: 3420 case AF_CXXNew: 3421 case AF_CXXNewArray: 3422 case AF_IfNameIndex: 3423 Msg = "Memory is released"; 3424 StackHint = std::make_unique<StackHintGeneratorForSymbol>( 3425 Sym, "Returning; memory was released"); 3426 break; 3427 case AF_InnerBuffer: { 3428 const MemRegion *ObjRegion = 3429 allocation_state::getContainerObjRegion(statePrev, Sym); 3430 const auto *TypedRegion = cast<TypedValueRegion>(ObjRegion); 3431 QualType ObjTy = TypedRegion->getValueType(); 3432 OS << "Inner buffer of '" << ObjTy << "' "; 3433 3434 if (N->getLocation().getKind() == ProgramPoint::PostImplicitCallKind) { 3435 OS << "deallocated by call to destructor"; 3436 StackHint = std::make_unique<StackHintGeneratorForSymbol>( 3437 Sym, "Returning; inner buffer was deallocated"); 3438 } else { 3439 OS << "reallocated by call to '"; 3440 const Stmt *S = RSCurr->getStmt(); 3441 if (const auto *MemCallE = dyn_cast<CXXMemberCallExpr>(S)) { 3442 OS << MemCallE->getMethodDecl()->getDeclName(); 3443 } else if (const auto *OpCallE = dyn_cast<CXXOperatorCallExpr>(S)) { 3444 OS << OpCallE->getDirectCallee()->getDeclName(); 3445 } else if (const auto *CallE = dyn_cast<CallExpr>(S)) { 3446 auto &CEMgr = BRC.getStateManager().getCallEventManager(); 3447 CallEventRef<> Call = CEMgr.getSimpleCall(CallE, state, CurrentLC); 3448 if (const auto *D = dyn_cast_or_null<NamedDecl>(Call->getDecl())) 3449 OS << D->getDeclName(); 3450 else 3451 OS << "unknown"; 3452 } 3453 OS << "'"; 3454 StackHint = std::make_unique<StackHintGeneratorForSymbol>( 3455 Sym, "Returning; inner buffer was reallocated"); 3456 } 3457 Msg = OS.str(); 3458 break; 3459 } 3460 case AF_None: 3461 llvm_unreachable("Unhandled allocation family!"); 3462 } 3463 3464 // See if we're releasing memory while inlining a destructor 3465 // (or one of its callees). This turns on various common 3466 // false positive suppressions. 3467 bool FoundAnyDestructor = false; 3468 for (const LocationContext *LC = CurrentLC; LC; LC = LC->getParent()) { 3469 if (const auto *DD = dyn_cast<CXXDestructorDecl>(LC->getDecl())) { 3470 if (isReferenceCountingPointerDestructor(DD)) { 3471 // This immediately looks like a reference-counting destructor. 3472 // We're bad at guessing the original reference count of the object, 3473 // so suppress the report for now. 3474 BR.markInvalid(getTag(), DD); 3475 } else if (!FoundAnyDestructor) { 3476 assert(!ReleaseDestructorLC && 3477 "There can be only one release point!"); 3478 // Suspect that it's a reference counting pointer destructor. 3479 // On one of the next nodes might find out that it has atomic 3480 // reference counting operations within it (see the code above), 3481 // and if so, we'd conclude that it likely is a reference counting 3482 // pointer destructor. 3483 ReleaseDestructorLC = LC->getStackFrame(); 3484 // It is unlikely that releasing memory is delegated to a destructor 3485 // inside a destructor of a shared pointer, because it's fairly hard 3486 // to pass the information that the pointer indeed needs to be 3487 // released into it. So we're only interested in the innermost 3488 // destructor. 3489 FoundAnyDestructor = true; 3490 } 3491 } 3492 } 3493 } else if (isRelinquished(RSCurr, RSPrev, S)) { 3494 Msg = "Memory ownership is transferred"; 3495 StackHint = std::make_unique<StackHintGeneratorForSymbol>(Sym, ""); 3496 } else if (hasReallocFailed(RSCurr, RSPrev, S)) { 3497 Mode = ReallocationFailed; 3498 Msg = "Reallocation failed"; 3499 StackHint = std::make_unique<StackHintGeneratorForReallocationFailed>( 3500 Sym, "Reallocation failed"); 3501 3502 if (SymbolRef sym = findFailedReallocSymbol(state, statePrev)) { 3503 // Is it possible to fail two reallocs WITHOUT testing in between? 3504 assert((!FailedReallocSymbol || FailedReallocSymbol == sym) && 3505 "We only support one failed realloc at a time."); 3506 BR.markInteresting(sym); 3507 FailedReallocSymbol = sym; 3508 } 3509 } 3510 3511 // We are in a special mode if a reallocation failed later in the path. 3512 } else if (Mode == ReallocationFailed) { 3513 assert(FailedReallocSymbol && "No symbol to look for."); 3514 3515 // Is this is the first appearance of the reallocated symbol? 3516 if (!statePrev->get<RegionState>(FailedReallocSymbol)) { 3517 // We're at the reallocation point. 3518 Msg = "Attempt to reallocate memory"; 3519 StackHint = std::make_unique<StackHintGeneratorForSymbol>( 3520 Sym, "Returned reallocated memory"); 3521 FailedReallocSymbol = nullptr; 3522 Mode = Normal; 3523 } 3524 } 3525 3526 if (Msg.empty()) { 3527 assert(!StackHint); 3528 return nullptr; 3529 } 3530 3531 assert(StackHint); 3532 3533 // Generate the extra diagnostic. 3534 PathDiagnosticLocation Pos; 3535 if (!S) { 3536 assert(RSCurr->getAllocationFamily() == AF_InnerBuffer); 3537 auto PostImplCall = N->getLocation().getAs<PostImplicitCall>(); 3538 if (!PostImplCall) 3539 return nullptr; 3540 Pos = PathDiagnosticLocation(PostImplCall->getLocation(), 3541 BRC.getSourceManager()); 3542 } else { 3543 Pos = PathDiagnosticLocation(S, BRC.getSourceManager(), 3544 N->getLocationContext()); 3545 } 3546 3547 auto P = std::make_shared<PathDiagnosticEventPiece>(Pos, Msg, true); 3548 BR.addCallStackHint(P, std::move(StackHint)); 3549 return P; 3550 } 3551 3552 void MallocChecker::printState(raw_ostream &Out, ProgramStateRef State, 3553 const char *NL, const char *Sep) const { 3554 3555 RegionStateTy RS = State->get<RegionState>(); 3556 3557 if (!RS.isEmpty()) { 3558 Out << Sep << "MallocChecker :" << NL; 3559 for (RegionStateTy::iterator I = RS.begin(), E = RS.end(); I != E; ++I) { 3560 const RefState *RefS = State->get<RegionState>(I.getKey()); 3561 AllocationFamily Family = RefS->getAllocationFamily(); 3562 Optional<MallocChecker::CheckKind> CheckKind = getCheckIfTracked(Family); 3563 if (!CheckKind) 3564 CheckKind = getCheckIfTracked(Family, true); 3565 3566 I.getKey()->dumpToStream(Out); 3567 Out << " : "; 3568 I.getData().dump(Out); 3569 if (CheckKind) 3570 Out << " (" << CheckNames[*CheckKind].getName() << ")"; 3571 Out << NL; 3572 } 3573 } 3574 } 3575 3576 namespace clang { 3577 namespace ento { 3578 namespace allocation_state { 3579 3580 ProgramStateRef 3581 markReleased(ProgramStateRef State, SymbolRef Sym, const Expr *Origin) { 3582 AllocationFamily Family = AF_InnerBuffer; 3583 return State->set<RegionState>(Sym, RefState::getReleased(Family, Origin)); 3584 } 3585 3586 } // end namespace allocation_state 3587 } // end namespace ento 3588 } // end namespace clang 3589 3590 // Intended to be used in InnerPointerChecker to register the part of 3591 // MallocChecker connected to it. 3592 void ento::registerInnerPointerCheckerAux(CheckerManager &mgr) { 3593 MallocChecker *checker = mgr.getChecker<MallocChecker>(); 3594 checker->ChecksEnabled[MallocChecker::CK_InnerPointerChecker] = true; 3595 checker->CheckNames[MallocChecker::CK_InnerPointerChecker] = 3596 mgr.getCurrentCheckerName(); 3597 } 3598 3599 void ento::registerDynamicMemoryModeling(CheckerManager &mgr) { 3600 auto *checker = mgr.registerChecker<MallocChecker>(); 3601 checker->ShouldIncludeOwnershipAnnotatedFunctions = 3602 mgr.getAnalyzerOptions().getCheckerBooleanOption(checker, "Optimistic"); 3603 checker->ShouldRegisterNoOwnershipChangeVisitor = 3604 mgr.getAnalyzerOptions().getCheckerBooleanOption( 3605 checker, "AddNoOwnershipChangeNotes"); 3606 } 3607 3608 bool ento::shouldRegisterDynamicMemoryModeling(const CheckerManager &mgr) { 3609 return true; 3610 } 3611 3612 #define REGISTER_CHECKER(name) \ 3613 void ento::register##name(CheckerManager &mgr) { \ 3614 MallocChecker *checker = mgr.getChecker<MallocChecker>(); \ 3615 checker->ChecksEnabled[MallocChecker::CK_##name] = true; \ 3616 checker->CheckNames[MallocChecker::CK_##name] = \ 3617 mgr.getCurrentCheckerName(); \ 3618 } \ 3619 \ 3620 bool ento::shouldRegister##name(const CheckerManager &mgr) { return true; } 3621 3622 REGISTER_CHECKER(MallocChecker) 3623 REGISTER_CHECKER(NewDeleteChecker) 3624 REGISTER_CHECKER(NewDeleteLeaksChecker) 3625 REGISTER_CHECKER(MismatchedDeallocatorChecker) 3626