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