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