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