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