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