clang 24.0.0git
MallocChecker.cpp
Go to the documentation of this file.
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 checkers that report memory management errors such as
10// leak, double free, and use-after-free.
11//
12// The logic for modeling memory allocations is implemented in the checker
13// family which is called 'MallocChecker' for historical reasons. (This name is
14// inaccurate, something like 'DynamicMemory' would be more precise.)
15//
16// The reports produced by this backend are exposed through several frontends:
17// * MallocChecker: reports all misuse of dynamic memory allocated by
18// malloc, related functions (like calloc, realloc etc.) and the functions
19// annotated by ownership_returns. (Here the name "MallocChecker" is
20// reasonably accurate; don't confuse this checker frontend with the whole
21// misnamed family.)
22// * NewDeleteChecker: reports most misuse (anything but memory leaks) of
23// memory managed by the C++ operators new and new[].
24// * NewDeleteLeaksChecker: reports leaks of dynamic memory allocated by
25// the C++ operators new and new[].
26// * MismatchedDeallocatorChecker: reports situations where the allocation
27// and deallocation is mismatched, e.g. memory allocated via malloc is
28// passed to operator delete.
29// * InnerPointerChecker: reports use of pointers to the internal buffer of
30// a std::string instance after operations that invalidate them.
31// * TaintedAllocChecker: reports situations where the size argument of a
32// memory allocation function or array new operator is tainted (i.e. comes
33// from an untrusted source and can be controlled by an attacker).
34//
35// In addition to these frontends this file also defines the registration
36// functions for "unix.DynamicMemoryModeling". This registers the callbacks of
37// the checker family MallocChecker without enabling any of the frontends and
38// and handle two checker options which are attached to this "modeling
39// checker" because they affect multiple checker frontends.
40//
41// Note that what the users see as the checker "cplusplus.InnerPointer" is a
42// combination of the frontend InnerPointerChecker (within this family) which
43// emits the bug reports and a separate checker class (also named
44// InnerPointerChecker) which is defined in InnerPointerChecker.cpp and does a
45// significant part of the modeling. This cooperation is enabled by several
46// non-static helper functions that are defined within this translation unit
47// and used in InnerPointerChecker.cpp.
48//
49//===----------------------------------------------------------------------===//
50
51#include "AllocationState.h"
52#include "InterCheckerAPI.h"
54#include "clang/AST/Attr.h"
55#include "clang/AST/DeclCXX.h"
57#include "clang/AST/Expr.h"
58#include "clang/AST/ExprCXX.h"
59#include "clang/AST/ParentMap.h"
63#include "clang/Basic/LLVM.h"
66#include "clang/Lex/Lexer.h"
84#include "llvm/ADT/STLExtras.h"
85#include "llvm/ADT/SmallVector.h"
86#include "llvm/ADT/StringExtras.h"
87#include "llvm/Support/Casting.h"
88#include "llvm/Support/Compiler.h"
89#include "llvm/Support/ErrorHandling.h"
90#include "llvm/Support/raw_ostream.h"
91#include <functional>
92#include <optional>
93#include <utility>
94
95using namespace clang;
96using namespace ento;
97using namespace std::placeholders;
98
99//===----------------------------------------------------------------------===//
100// The types of allocation we're modeling. This is used to check whether a
101// dynamically allocated object is deallocated with the correct function, like
102// not using operator delete on an object created by malloc(), or alloca regions
103// aren't ever deallocated manually.
104//===----------------------------------------------------------------------===//
105
106namespace {
107
108// Used to check correspondence between allocators and deallocators.
109enum AllocationFamilyKind {
110 AF_None,
111 AF_Malloc,
112 AF_CXXNew,
113 AF_CXXNewArray,
114 AF_IfNameIndex,
115 AF_Alloca,
116 AF_InnerBuffer,
117 AF_Custom,
118};
119
120struct AllocationFamily {
121 AllocationFamilyKind Kind;
122 std::optional<StringRef> CustomName;
123
124 explicit AllocationFamily(AllocationFamilyKind AKind,
125 std::optional<StringRef> Name = std::nullopt)
126 : Kind(AKind), CustomName(Name) {
127 assert((Kind != AF_Custom || CustomName.has_value()) &&
128 "Custom family must specify also the name");
129
130 // Preseve previous behavior when "malloc" class means AF_Malloc
131 if (Kind == AF_Custom && CustomName.value() == "malloc") {
132 Kind = AF_Malloc;
133 CustomName = std::nullopt;
134 }
135 }
136
137 bool operator==(const AllocationFamily &Other) const {
138 return std::tie(Kind, CustomName) == std::tie(Other.Kind, Other.CustomName);
139 }
140
141 bool operator!=(const AllocationFamily &Other) const {
142 return !(*this == Other);
143 }
144
145 void Profile(llvm::FoldingSetNodeID &ID) const {
146 ID.AddInteger(Kind);
147
148 if (Kind == AF_Custom)
149 ID.AddString(CustomName.value());
150 }
151};
152
153} // end of anonymous namespace
154
155/// Print names of allocators and deallocators.
156///
157/// \returns true on success.
158static bool printMemFnName(raw_ostream &os, CheckerContext &C, const Expr *E);
159
160/// Print expected name of an allocator based on the deallocator's family
161/// derived from the DeallocExpr.
162static void printExpectedAllocName(raw_ostream &os, AllocationFamily Family);
163
164/// Print expected name of a deallocator based on the allocator's
165/// family.
166static void printExpectedDeallocName(raw_ostream &os, AllocationFamily Family);
167
168//===----------------------------------------------------------------------===//
169// The state of a symbol, in terms of memory management.
170//===----------------------------------------------------------------------===//
171
172namespace {
173
174class RefState {
175 enum Kind {
176 // Reference to allocated memory, no information about allocation size.
177 AllocatedOfAnySize,
178 // Reference to zero-allocated memory.
179 AllocatedOfSizeZero,
180 // Reference to released/freed memory.
181 Released,
182 // The responsibility for freeing resources has transferred from
183 // this reference. A relinquished symbol should not be freed.
184 Relinquished,
185 // We are no longer guaranteed to have observed all manipulations
186 // of this pointer/memory. For example, it could have been
187 // passed as a parameter to an opaque function.
188 Escaped
189 };
190
191 const Stmt *S;
192
193 Kind K;
194 AllocationFamily Family;
195
196 RefState(Kind k, const Stmt *s, AllocationFamily family)
197 : S(s), K(k), Family(family) {
198 assert(family.Kind != AF_None);
199 }
200
201public:
202 bool isAllocated() const {
203 return K == AllocatedOfAnySize || K == AllocatedOfSizeZero;
204 }
205 bool isAllocatedOfSizeZero() const { return K == AllocatedOfSizeZero; }
206 bool isReleased() const { return K == Released; }
207 bool isRelinquished() const { return K == Relinquished; }
208 bool isEscaped() const { return K == Escaped; }
209 AllocationFamily getAllocationFamily() const { return Family; }
210 const Stmt *getStmt() const { return S; }
211
212 bool operator==(const RefState &X) const {
213 return K == X.K && S == X.S && Family == X.Family;
214 }
215
216 static RefState getAllocated(AllocationFamily F, const Stmt *S) {
217 return RefState(AllocatedOfAnySize, S, F);
218 }
219 static RefState getAllocatedOfSizeZero(const RefState *RS) {
220 return RefState(AllocatedOfSizeZero, RS->getStmt(),
221 RS->getAllocationFamily());
222 }
223 static RefState getReleased(AllocationFamily family, const Stmt *s) {
224 return RefState(Released, s, family);
225 }
226 static RefState getRelinquished(AllocationFamily family, const Stmt *s) {
227 return RefState(Relinquished, s, family);
228 }
229 static RefState getEscaped(const RefState *RS) {
230 return RefState(Escaped, RS->getStmt(), RS->getAllocationFamily());
231 }
232
233 void Profile(llvm::FoldingSetNodeID &ID) const {
234 ID.AddInteger(K);
235 ID.AddPointer(S);
236 Family.Profile(ID);
237 }
238
239 LLVM_DUMP_METHOD void dump(raw_ostream &OS) const {
240 switch (K) {
241 case AllocatedOfAnySize:
242 OS << "Allocated";
243 break;
244#define CASE(ID) case ID: OS << #ID; break;
245 CASE(AllocatedOfSizeZero)
246 CASE(Released)
247 CASE(Relinquished)
248 CASE(Escaped)
249 }
250 }
251
252 LLVM_DUMP_METHOD void dump() const { dump(llvm::errs()); }
253};
254
255} // end of anonymous namespace
256
257REGISTER_MAP_WITH_PROGRAMSTATE(RegionState, SymbolRef, RefState)
258
259/// Check if the memory associated with this symbol was released.
260static bool isReleased(SymbolRef Sym, CheckerContext &C);
261
262/// Update the RefState to reflect the new memory allocation.
263/// The optional \p RetVal parameter specifies the newly allocated pointer
264/// value; if unspecified, the value of expression \p E is used.
265static ProgramStateRef
267 AllocationFamily Family,
268 std::optional<SVal> RetVal = std::nullopt);
269
270//===----------------------------------------------------------------------===//
271// The modeling of memory reallocation.
272//
273// The terminology 'toPtr' and 'fromPtr' will be used:
274// toPtr = realloc(fromPtr, 20);
275//===----------------------------------------------------------------------===//
276
277REGISTER_SET_WITH_PROGRAMSTATE(ReallocSizeZeroSymbols, SymbolRef)
278
279namespace {
280
281/// The state of 'fromPtr' after reallocation is known to have failed.
282enum OwnershipAfterReallocKind {
283 // The symbol needs to be freed (e.g.: realloc)
284 OAR_ToBeFreedAfterFailure,
285 // The symbol has been freed (e.g.: reallocf)
286 OAR_FreeOnFailure,
287 // The symbol doesn't have to freed (e.g.: we aren't sure if, how and where
288 // 'fromPtr' was allocated:
289 // void Haha(int *ptr) {
290 // ptr = realloc(ptr, 67);
291 // // ...
292 // }
293 // ).
294 OAR_DoNotTrackAfterFailure
295};
296
297/// Stores information about the 'fromPtr' symbol after reallocation.
298///
299/// This is important because realloc may fail, and that needs special modeling.
300/// Whether reallocation failed or not will not be known until later, so we'll
301/// store whether upon failure 'fromPtr' will be freed, or needs to be freed
302/// later, etc.
303struct ReallocPair {
304
305 // The 'fromPtr'.
306 SymbolRef ReallocatedSym;
307 OwnershipAfterReallocKind Kind;
308
309 ReallocPair(SymbolRef S, OwnershipAfterReallocKind K)
310 : ReallocatedSym(S), Kind(K) {}
311 void Profile(llvm::FoldingSetNodeID &ID) const {
312 ID.AddInteger(Kind);
313 ID.AddPointer(ReallocatedSym);
314 }
315 bool operator==(const ReallocPair &X) const {
316 return ReallocatedSym == X.ReallocatedSym &&
317 Kind == X.Kind;
318 }
319};
320
321} // end of anonymous namespace
322
323REGISTER_MAP_WITH_PROGRAMSTATE(ReallocPairs, SymbolRef, ReallocPair)
324
325static bool isStandardNew(const FunctionDecl *FD);
326static bool isStandardNew(const CallEvent &Call) {
327 if (!Call.getDecl() || !isa<FunctionDecl>(Call.getDecl()))
328 return false;
329 return isStandardNew(cast<FunctionDecl>(Call.getDecl()));
330}
331
332static bool isStandardDelete(const FunctionDecl *FD);
333static bool isStandardDelete(const CallEvent &Call) {
334 if (!Call.getDecl() || !isa<FunctionDecl>(Call.getDecl()))
335 return false;
336 return isStandardDelete(cast<FunctionDecl>(Call.getDecl()));
337}
338
339/// Tells if the callee is one of the builtin new/delete operators, including
340/// placement operators and other standard overloads.
341template <typename T> static bool isStandardNewDelete(const T &FD) {
342 return isStandardDelete(FD) || isStandardNew(FD);
343}
344
345namespace {
346
347//===----------------------------------------------------------------------===//
348// Utility classes that provide access to the bug types and can model that some
349// of the bug types are shared by multiple checker frontends.
350//===----------------------------------------------------------------------===//
351
352#define BUGTYPE_PROVIDER(NAME, DEF) \
353 struct NAME : virtual public CheckerFrontend { \
354 BugType NAME##Bug{this, DEF, categories::MemoryError}; \
355 };
356
357BUGTYPE_PROVIDER(DoubleFree, "Double free")
358
359struct Leak : virtual public CheckerFrontend {
360 // Leaks should not be reported if they are post-dominated by a sink:
361 // (1) Sinks are higher importance bugs.
362 // (2) NoReturnFunctionChecker uses sink nodes to represent paths ending
363 // with __noreturn functions such as assert() or exit(). We choose not
364 // to report leaks on such paths.
365 BugType LeakBug{this, "Memory leak", categories::MemoryError,
366 /*SuppressOnSink=*/true};
367};
368
369BUGTYPE_PROVIDER(UseFree, "Use-after-free")
370BUGTYPE_PROVIDER(BadFree, "Bad free")
371BUGTYPE_PROVIDER(FreeAlloca, "Free 'alloca()'")
372BUGTYPE_PROVIDER(MismatchedDealloc, "Bad deallocator")
373BUGTYPE_PROVIDER(OffsetFree, "Offset free")
374BUGTYPE_PROVIDER(UseZeroAllocated, "Use of zero allocated")
375
376#undef BUGTYPE_PROVIDER
377
378template <typename... BT_PROVIDERS>
379struct DynMemFrontend : virtual public CheckerFrontend, public BT_PROVIDERS... {
380 template <typename T> const T *getAs() const {
381 if constexpr (std::is_same_v<T, CheckerFrontend> ||
382 (std::is_same_v<T, BT_PROVIDERS> || ...))
383 return static_cast<const T *>(this);
384 return nullptr;
385 }
386};
387
388//===----------------------------------------------------------------------===//
389// Definition of the MallocChecker class.
390//===----------------------------------------------------------------------===//
391
392class MallocChecker
393 : public CheckerFamily<
394 check::DeadSymbols, check::PointerEscape, check::ConstPointerEscape,
395 check::PreStmt<ReturnStmt>, check::EndFunction, check::PreCall,
396 check::PostCall, eval::Call, check::NewAllocator,
397 check::PostStmt<BlockExpr>, check::PostObjCMessage, check::Location,
398 eval::Assume> {
399public:
400 /// In pessimistic mode, the checker assumes that it does not know which
401 /// functions might free the memory.
402 /// In optimistic mode, the checker assumes that all user-defined functions
403 /// which might free a pointer are annotated.
404 bool ShouldIncludeOwnershipAnnotatedFunctions = false;
405
406 bool ShouldRegisterNoOwnershipChangeVisitor = false;
407
408 /// Add extra branches for allocation failure. Generally a return value of an
409 /// allocation function is not constrained to be null or non-null and
410 /// information about a later null pointer access can be lost. When failure
411 /// branches are added, they contain the constrained null pointer return value
412 /// and allow detection of a null pointer access if the result of an
413 /// allocation is not checked for null.
414 bool ModelAllocationFailure = false;
415
416 // This checker family implements many bug types and frontends, and several
417 // bug types are shared between multiple frontends, so most of the frontends
418 // are declared with the helper class DynMemFrontend.
419 // FIXME: There is no clear reason for separating NewDelete vs NewDeleteLeaks
420 // while e.g. MallocChecker covers both non-leak and leak bugs together. It
421 // would be nice to redraw the boundaries between the frontends in a more
422 // logical way.
423 DynMemFrontend<DoubleFree, Leak, UseFree, BadFree, FreeAlloca, OffsetFree,
424 UseZeroAllocated>
425 MallocChecker;
426 DynMemFrontend<DoubleFree, UseFree, BadFree, OffsetFree, UseZeroAllocated>
427 NewDeleteChecker;
428 DynMemFrontend<Leak> NewDeleteLeaksChecker;
429 DynMemFrontend<FreeAlloca, MismatchedDealloc> MismatchedDeallocatorChecker;
430 DynMemFrontend<UseFree> InnerPointerChecker;
431 // This last frontend is associated with a single bug type which is not used
432 // elsewhere and has a different bug category, so it's declared separately.
433 CheckerFrontendWithBugType TaintedAllocChecker{"Tainted Memory Allocation",
435
436 using LeakInfo = std::pair<const ExplodedNode *, const MemRegion *>;
437
438 void checkPreCall(const CallEvent &Call, CheckerContext &C) const;
439 void checkPostCall(const CallEvent &Call, CheckerContext &C) const;
440 bool evalCall(const CallEvent &Call, CheckerContext &C) const;
441
443 handleSmartPointerConstructorArguments(const CallEvent &Call,
444 ProgramStateRef State) const;
445 ProgramStateRef handleSmartPointerRelatedCalls(const CallEvent &Call,
446 CheckerContext &C,
447 ProgramStateRef State) const;
448 void checkNewAllocator(const CXXAllocatorCall &Call, CheckerContext &C) const;
449 void checkPostObjCMessage(const ObjCMethodCall &Call, CheckerContext &C) const;
450 void checkPostStmt(const BlockExpr *BE, CheckerContext &C) const;
451 void checkDeadSymbols(SymbolReaper &SymReaper, CheckerContext &C) const;
452 void checkPreStmt(const ReturnStmt *S, CheckerContext &C) const;
453 void checkEndFunction(const ReturnStmt *S, CheckerContext &C) const;
454 ProgramStateRef evalAssume(ProgramStateRef state, SVal Cond,
455 bool Assumption) const;
456 void checkLocation(SVal l, bool isLoad, const Stmt *S,
457 CheckerContext &C) const;
458
459 ProgramStateRef checkPointerEscape(ProgramStateRef State,
460 const InvalidatedSymbols &Escaped,
461 const CallEvent *Call,
462 PointerEscapeKind Kind) const;
463 ProgramStateRef checkConstPointerEscape(ProgramStateRef State,
464 const InvalidatedSymbols &Escaped,
465 const CallEvent *Call,
466 PointerEscapeKind Kind) const;
467
468 void printState(raw_ostream &Out, ProgramStateRef State,
469 const char *NL, const char *Sep) const override;
470
471 StringRef getDebugTag() const override { return "MallocChecker"; }
472
473private:
474#define CHECK_FN(NAME) \
475 void NAME(ProgramStateRef State, const CallEvent &Call, CheckerContext &C) \
476 const;
477
478 CHECK_FN(checkFree)
479 CHECK_FN(checkIfNameIndex)
480 CHECK_FN(checkBasicAlloc)
481 CHECK_FN(checkBasicAllocMayFail)
482 CHECK_FN(checkKernelMalloc)
483 CHECK_FN(checkCalloc)
484 CHECK_FN(checkAlloca)
485 CHECK_FN(checkStrdup)
486 CHECK_FN(checkIfFreeNameIndex)
487 CHECK_FN(checkCXXNewOrCXXDelete)
488 CHECK_FN(checkGMalloc0)
489 CHECK_FN(checkGMemdup)
490 CHECK_FN(checkGMallocN)
491 CHECK_FN(checkGMallocN0)
492 CHECK_FN(preGetDelimOrGetLine)
493 CHECK_FN(checkGetDelimOrGetLine)
494 CHECK_FN(checkReallocN)
495 CHECK_FN(checkOwnershipAttr)
496
497 void checkRealloc(ProgramStateRef State, const CallEvent &Call,
498 CheckerContext &C, bool ShouldFreeOnFail) const;
499
500 using CheckFn =
501 std::function<void(const class MallocChecker *, ProgramStateRef State,
502 const CallEvent &Call, CheckerContext &C)>;
503
504 const CallDescriptionMap<CheckFn> PreFnMap{
505 // NOTE: the following CallDescription also matches the C++ standard
506 // library function std::getline(); the callback will filter it out.
507 {{CDM::CLibrary, {"getline"}, 3}, &MallocChecker::preGetDelimOrGetLine},
508 {{CDM::CLibrary, {"getdelim"}, 4}, &MallocChecker::preGetDelimOrGetLine},
509 };
510
511 const CallDescriptionMap<CheckFn> PostFnMap{
512 // NOTE: the following CallDescription also matches the C++ standard
513 // library function std::getline(); the callback will filter it out.
514 {{CDM::CLibrary, {"getline"}, 3}, &MallocChecker::checkGetDelimOrGetLine},
515 {{CDM::CLibrary, {"getdelim"}, 4},
516 &MallocChecker::checkGetDelimOrGetLine},
517 };
518
519 const CallDescriptionMap<CheckFn> FreeingMemFnMap{
520 {{CDM::CLibrary, {"free"}, 1}, &MallocChecker::checkFree},
521 {{CDM::CLibrary, {"if_freenameindex"}, 1},
522 &MallocChecker::checkIfFreeNameIndex},
523 {{CDM::CLibrary, {"kfree"}, 1}, &MallocChecker::checkFree},
524 {{CDM::CLibrary, {"g_free"}, 1}, &MallocChecker::checkFree},
525 };
526
527 bool isFreeingCall(const CallEvent &Call) const;
528 static bool isFreeingOwnershipAttrCall(const FunctionDecl *Func);
529 static bool isFreeingOwnershipAttrCall(const CallEvent &Call);
530 static bool isAllocatingOwnershipAttrCall(const FunctionDecl *Func);
531 static bool isAllocatingOwnershipAttrCall(const CallEvent &Call);
532
533 friend class NoMemOwnershipChangeVisitor;
534
535 CallDescriptionMap<CheckFn> AllocaMemFnMap{
536 {{CDM::CLibrary, {"alloca"}, 1}, &MallocChecker::checkAlloca},
537 {{CDM::CLibrary, {"_alloca"}, 1}, &MallocChecker::checkAlloca},
538 // The line for "alloca" also covers "__builtin_alloca", but the
539 // _with_align variant must be listed separately because it takes an
540 // extra argument:
541 {{CDM::CLibrary, {"__builtin_alloca_with_align"}, 2},
542 &MallocChecker::checkAlloca},
543 };
544
545 CallDescriptionMap<CheckFn> AllocatingMemFnMap{
546 {{CDM::CLibrary, {"malloc"}, 1}, &MallocChecker::checkBasicAllocMayFail},
547 {{CDM::CLibrary, {"malloc"}, 3}, &MallocChecker::checkKernelMalloc},
548 {{CDM::CLibrary, {"calloc"}, 2}, &MallocChecker::checkCalloc},
549 {{CDM::CLibrary, {"valloc"}, 1}, &MallocChecker::checkBasicAlloc},
550 {{CDM::CLibrary, {"strndup"}, 2}, &MallocChecker::checkStrdup},
551 {{CDM::CLibrary, {"strdup"}, 1}, &MallocChecker::checkStrdup},
552 {{CDM::CLibrary, {"_strdup"}, 1}, &MallocChecker::checkStrdup},
553 {{CDM::CLibrary, {"kmalloc"}, 2}, &MallocChecker::checkKernelMalloc},
554 {{CDM::CLibrary, {"if_nameindex"}, 0}, &MallocChecker::checkIfNameIndex},
555 {{CDM::CLibrary, {"wcsdup"}, 1}, &MallocChecker::checkStrdup},
556 {{CDM::CLibrary, {"_wcsdup"}, 1}, &MallocChecker::checkStrdup},
557 {{CDM::CLibrary, {"g_malloc"}, 1}, &MallocChecker::checkBasicAlloc},
558 {{CDM::CLibrary, {"g_malloc0"}, 1}, &MallocChecker::checkGMalloc0},
559 {{CDM::CLibrary, {"g_try_malloc"}, 1}, &MallocChecker::checkBasicAlloc},
560 {{CDM::CLibrary, {"g_try_malloc0"}, 1}, &MallocChecker::checkGMalloc0},
561 {{CDM::CLibrary, {"g_memdup"}, 2}, &MallocChecker::checkGMemdup},
562 {{CDM::CLibrary, {"g_malloc_n"}, 2}, &MallocChecker::checkGMallocN},
563 {{CDM::CLibrary, {"g_malloc0_n"}, 2}, &MallocChecker::checkGMallocN0},
564 {{CDM::CLibrary, {"g_try_malloc_n"}, 2}, &MallocChecker::checkGMallocN},
565 {{CDM::CLibrary, {"g_try_malloc0_n"}, 2}, &MallocChecker::checkGMallocN0},
566 };
567
568 CallDescriptionMap<CheckFn> ReallocatingMemFnMap{
569 {{CDM::CLibrary, {"realloc"}, 2},
570 std::bind(&MallocChecker::checkRealloc, _1, _2, _3, _4, false)},
571 {{CDM::CLibrary, {"reallocf"}, 2},
572 std::bind(&MallocChecker::checkRealloc, _1, _2, _3, _4, true)},
573 {{CDM::CLibrary, {"g_realloc"}, 2},
574 std::bind(&MallocChecker::checkRealloc, _1, _2, _3, _4, false)},
575 {{CDM::CLibrary, {"g_try_realloc"}, 2},
576 std::bind(&MallocChecker::checkRealloc, _1, _2, _3, _4, false)},
577 {{CDM::CLibrary, {"g_realloc_n"}, 3}, &MallocChecker::checkReallocN},
578 {{CDM::CLibrary, {"g_try_realloc_n"}, 3}, &MallocChecker::checkReallocN},
579 };
580
581 bool isMemCall(const CallEvent &Call) const;
582 void reportTaintBug(StringRef Msg, ProgramStateRef State, CheckerContext &C,
583 llvm::ArrayRef<SymbolRef> TaintedSyms,
584 AllocationFamily Family) const;
585
586 void checkTaintedness(CheckerContext &C, const CallEvent &Call,
587 const SVal SizeSVal, ProgramStateRef State,
588 AllocationFamily Family) const;
589
590 // TODO: Remove mutable by moving the initializtaion to the registry function.
591 mutable std::optional<uint64_t> KernelZeroFlagVal;
592
593 using KernelZeroSizePtrValueTy = std::optional<int>;
594 /// Store the value of macro called `ZERO_SIZE_PTR`.
595 /// The value is initialized at first use, before first use the outer
596 /// Optional is empty, afterwards it contains another Optional that indicates
597 /// if the macro value could be determined, and if yes the value itself.
598 mutable std::optional<KernelZeroSizePtrValueTy> KernelZeroSizePtrValue;
599
600 /// Process C++ operator new()'s allocation, which is the part of C++
601 /// new-expression that goes before the constructor.
602 [[nodiscard]] ProgramStateRef
603 processNewAllocation(const CXXAllocatorCall &Call, CheckerContext &C,
604 AllocationFamily Family) const;
605
606 /// Perform a zero-allocation check.
607 ///
608 /// \param [in] Call The expression that allocates memory.
609 /// \param [in] IndexOfSizeArg Index of the argument that specifies the size
610 /// of the memory that needs to be allocated. E.g. for malloc, this would be
611 /// 0.
612 /// \param [in] RetVal Specifies the newly allocated pointer value;
613 /// if unspecified, the value of expression \p E is used.
614 [[nodiscard]] static ProgramStateRef
615 ProcessZeroAllocCheck(CheckerContext &C, const CallEvent &Call,
616 const unsigned IndexOfSizeArg, ProgramStateRef State,
617 std::optional<SVal> RetVal = std::nullopt);
618
619 /// Model functions with the ownership_returns attribute.
620 ///
621 /// User-defined function may have the ownership_returns attribute, which
622 /// annotates that the function returns with an object that was allocated on
623 /// the heap, and passes the ownertship to the callee.
624 ///
625 /// void __attribute((ownership_returns(malloc, 1))) *my_malloc(size_t);
626 ///
627 /// It has two parameters:
628 /// - first: name of the resource (e.g. 'malloc')
629 /// - (OPTIONAL) second: size of the allocated region
630 ///
631 /// \param [in] Call The expression that allocates memory.
632 /// \param [in] Att The ownership_returns attribute.
633 /// \param [in] State The \c ProgramState right before allocation.
634 /// \returns The ProgramState right after allocation.
635 [[nodiscard]] ProgramStateRef
636 MallocMemReturnsAttr(CheckerContext &C, const CallEvent &Call,
637 const OwnershipAttr *Att, ProgramStateRef State) const;
638 /// Models memory allocation.
639 ///
640 /// \param [in] C Checker context.
641 /// \param [in] Call The expression that allocates memory.
642 /// \param [in] State The \c ProgramState right before allocation.
643 /// \param [in] isAlloca Is the allocation function alloca-like
644 /// \returns The ProgramState with returnValue bound
645 [[nodiscard]] ProgramStateRef MallocBindRetVal(CheckerContext &C,
646 const CallEvent &Call,
647 ProgramStateRef State,
648 bool isAlloca) const;
649
650 /// Models memory allocation.
651 ///
652 /// \param [in] Call The expression that allocates memory.
653 /// \param [in] SizeEx Size of the memory that needs to be allocated.
654 /// \param [in] Init The value the allocated memory needs to be initialized.
655 /// with. For example, \c calloc initializes the allocated memory to 0,
656 /// malloc leaves it undefined.
657 /// \param [in] State The \c ProgramState right before allocation.
658 /// \returns The ProgramState right after allocation.
659 [[nodiscard]] ProgramStateRef
660 MallocMemAux(CheckerContext &C, const CallEvent &Call, const Expr *SizeEx,
661 SVal Init, ProgramStateRef State, AllocationFamily Family) const;
662
663 /// Models memory allocation.
664 ///
665 /// \param [in] Call The expression that allocates memory.
666 /// \param [in] Size Size of the memory that needs to be allocated.
667 /// \param [in] Init The value the allocated memory needs to be initialized.
668 /// with. For example, \c calloc initializes the allocated memory to 0,
669 /// malloc leaves it undefined.
670 /// \param [in] State The \c ProgramState right before allocation.
671 /// \returns The ProgramState right after allocation.
672 [[nodiscard]] ProgramStateRef MallocMemAux(CheckerContext &C,
673 const CallEvent &Call, SVal Size,
674 SVal Init, ProgramStateRef State,
675 AllocationFamily Family) const;
676
677 /// Models a non-successful memory allocation.
678 /// Can be used if the allocation function may return null on failure when the
679 /// size to be allocated is non-zero.
680 ///
681 /// \param [in] Call The expression that allocates memory.
682 /// \param [in] State The \c ProgramState right before allocation.
683 /// \param [in] SizeArgIndexes Indexes of arguments that specify the
684 /// allocation size.
685 /// \returns The ProgramState right after an unsuccessful allocation.
686 [[nodiscard]] ProgramStateRef
687 FailedAlloc(CheckerContext &C, const CallEvent &Call, ProgramStateRef State,
688 llvm::ArrayRef<unsigned> SizeArgIndexes = {}) const;
689
690 // Check if this malloc() for special flags. At present that means M_ZERO or
691 // __GFP_ZERO (in which case, treat it like calloc).
692 [[nodiscard]] std::optional<ProgramStateRef>
693 performKernelMalloc(const CallEvent &Call, CheckerContext &C,
694 const ProgramStateRef &State) const;
695
696 /// Model functions with the ownership_takes and ownership_holds attributes.
697 ///
698 /// User-defined function may have the ownership_takes and/or ownership_holds
699 /// attributes, which annotates that the function frees the memory passed as a
700 /// parameter.
701 ///
702 /// void __attribute((ownership_takes(malloc, 1))) my_free(void *);
703 /// void __attribute((ownership_holds(malloc, 1))) my_hold(void *);
704 ///
705 /// They have two parameters:
706 /// - first: name of the resource (e.g. 'malloc')
707 /// - second: index of the parameter the attribute applies to
708 ///
709 /// \param [in] Call The expression that frees memory.
710 /// \param [in] Att The ownership_takes or ownership_holds attribute.
711 /// \param [in] State The \c ProgramState right before allocation.
712 /// \returns The ProgramState right after deallocation.
713 [[nodiscard]] ProgramStateRef FreeMemAttr(CheckerContext &C,
714 const CallEvent &Call,
715 const OwnershipAttr *Att,
716 ProgramStateRef State) const;
717
718 /// Models memory deallocation.
719 ///
720 /// \param [in] Call The expression that frees memory.
721 /// \param [in] State The \c ProgramState right before allocation.
722 /// \param [in] Num Index of the argument that needs to be freed. This is
723 /// normally 0, but for custom free functions it may be different.
724 /// \param [in] Hold Whether the parameter at \p Index has the ownership_holds
725 /// attribute.
726 /// \param [out] IsKnownToBeAllocated Whether the memory to be freed is known
727 /// to have been allocated, or in other words, the symbol to be freed was
728 /// registered as allocated by this checker. In the following case, \c ptr
729 /// isn't known to be allocated.
730 /// void Haha(int *ptr) {
731 /// ptr = realloc(ptr, 67);
732 /// // ...
733 /// }
734 /// \param [in] ReturnsNullOnFailure Whether the memory deallocation function
735 /// we're modeling returns with Null on failure.
736 /// \returns The ProgramState right after deallocation.
737 [[nodiscard]] ProgramStateRef
738 FreeMemAux(CheckerContext &C, const CallEvent &Call, ProgramStateRef State,
739 unsigned Num, bool Hold, bool &IsKnownToBeAllocated,
740 AllocationFamily Family, bool ReturnsNullOnFailure = false) const;
741
742 /// Models memory deallocation.
743 ///
744 /// \param [in] ArgExpr The variable who's pointee needs to be freed.
745 /// \param [in] Call The expression that frees the memory.
746 /// \param [in] State The \c ProgramState right before allocation.
747 /// normally 0, but for custom free functions it may be different.
748 /// \param [in] Hold Whether the parameter at \p Index has the ownership_holds
749 /// attribute.
750 /// \param [out] IsKnownToBeAllocated Whether the memory to be freed is known
751 /// to have been allocated, or in other words, the symbol to be freed was
752 /// registered as allocated by this checker. In the following case, \c ptr
753 /// isn't known to be allocated.
754 /// void Haha(int *ptr) {
755 /// ptr = realloc(ptr, 67);
756 /// // ...
757 /// }
758 /// \param [in] ReturnsNullOnFailure Whether the memory deallocation function
759 /// we're modeling returns with Null on failure.
760 /// \param [in] ArgValOpt Optional value to use for the argument instead of
761 /// the one obtained from ArgExpr.
762 /// \returns The ProgramState right after deallocation.
763 [[nodiscard]] ProgramStateRef
764 FreeMemAux(CheckerContext &C, const Expr *ArgExpr, const CallEvent &Call,
765 ProgramStateRef State, bool Hold, bool &IsKnownToBeAllocated,
766 AllocationFamily Family, bool ReturnsNullOnFailure = false,
767 std::optional<SVal> ArgValOpt = {}) const;
768
769 // TODO: Needs some refactoring, as all other deallocation modeling
770 // functions are suffering from out parameters and messy code due to how
771 // realloc is handled.
772 //
773 /// Models memory reallocation.
774 ///
775 /// \param [in] Call The expression that reallocated memory
776 /// \param [in] ShouldFreeOnFail Whether if reallocation fails, the supplied
777 /// memory should be freed.
778 /// \param [in] State The \c ProgramState right before reallocation.
779 /// \param [in] SuffixWithN Whether the reallocation function we're modeling
780 /// has an '_n' suffix, such as g_realloc_n.
781 /// \returns The ProgramState right after reallocation.
782 [[nodiscard]] ProgramStateRef
783 ReallocMemAux(CheckerContext &C, const CallEvent &Call, bool ShouldFreeOnFail,
784 ProgramStateRef State, AllocationFamily Family,
785 bool SuffixWithN = false) const;
786
787 /// Evaluates the buffer size that needs to be allocated.
788 ///
789 /// \param [in] Blocks The amount of blocks that needs to be allocated.
790 /// \param [in] BlockBytes The size of a block.
791 /// \returns The symbolic value of \p Blocks * \p BlockBytes.
792 [[nodiscard]] static SVal evalMulForBufferSize(CheckerContext &C,
793 const Expr *Blocks,
794 const Expr *BlockBytes);
795
796 /// Models zero initialized array allocation.
797 ///
798 /// \param [in] Call The expression that reallocated memory
799 /// \param [in] State The \c ProgramState right before reallocation.
800 /// \returns The ProgramState right after allocation.
801 [[nodiscard]] ProgramStateRef CallocMem(CheckerContext &C,
802 const CallEvent &Call,
803 ProgramStateRef State) const;
804
805 /// See if deallocation happens in a suspicious context. If so, escape the
806 /// pointers that otherwise would have been deallocated and return true.
807 bool suppressDeallocationsInSuspiciousContexts(const CallEvent &Call,
808 CheckerContext &C) const;
809
810 /// If in \p S \p Sym is used, check whether \p Sym was already freed.
811 bool checkUseAfterFree(SymbolRef Sym, CheckerContext &C, const Stmt *S) const;
812
813 /// If in \p S \p Sym is used, check whether \p Sym was allocated as a zero
814 /// sized memory region.
815 void checkUseZeroAllocated(SymbolRef Sym, CheckerContext &C,
816 const Stmt *S) const;
817
818 /// Return true if this checker can continue to follow the state of pointers
819 /// that are passed directly (as arguments) to the opaque call \p Call.
820 /// By default a pointer passed to an opaque call would be marked as
821 /// "escaped" (i.e. using it, releasing it and not releasing it are all
822 /// accepted as potentially valid) but if the called function is from a
823 /// system header we can often see that it won't release the memory.
824 ///
825 /// \param [out] EscapingSymbol A function might not free memory in general,
826 /// but could be known to free a particular symbol. In this case, false is
827 /// returned and the single escaping symbol is returned through the out
828 /// parameter.
829 bool ignoreDirectEscapeTo(const CallEvent *Call,
830 SymbolRef &EscapingSymbol) const;
831
832 /// Implementation of the checkPointerEscape callbacks.
833 [[nodiscard]] ProgramStateRef
834 checkPointerEscapeAux(ProgramStateRef State,
835 const InvalidatedSymbols &Escaped,
836 const CallEvent *Call, PointerEscapeKind Kind,
837 bool IsConstPointerEscape) const;
838
839 // Implementation of the checkPreStmt and checkEndFunction callbacks.
840 void checkEscapeOnReturn(const ReturnStmt *S, CheckerContext &C) const;
841
842 ///@{
843 /// Returns a pointer to the checker frontend corresponding to the given
844 /// family or symbol. The template argument T may be either CheckerFamily or
845 /// a BUGTYPE_PROVIDER class; in the latter case the query is restricted to
846 /// frontends that descend from that PROVIDER class (i.e. can emit that bug
847 /// type). Note that this may return a frontend which is disabled.
848 template <class T>
849 const T *getRelevantFrontendAs(AllocationFamily Family) const;
850
851 template <class T>
852 const T *getRelevantFrontendAs(CheckerContext &C, SymbolRef Sym) const;
853 ///@}
854 static bool SummarizeValue(raw_ostream &os, SVal V);
855 static bool SummarizeRegion(ProgramStateRef State, raw_ostream &os,
856 const MemRegion *MR);
857
858 void HandleNonHeapDealloc(CheckerContext &C, SVal ArgVal, SourceRange Range,
859 const Expr *DeallocExpr,
860 AllocationFamily Family) const;
861
862 void HandleFreeAlloca(CheckerContext &C, SVal ArgVal,
863 SourceRange Range) const;
864
865 void HandleMismatchedDealloc(CheckerContext &C, SourceRange Range,
866 const Expr *DeallocExpr, const RefState *RS,
867 SymbolRef Sym, bool OwnershipTransferred) const;
868
869 void HandleOffsetFree(CheckerContext &C, SVal ArgVal, SourceRange Range,
870 const Expr *DeallocExpr, AllocationFamily Family,
871 const Expr *AllocExpr = nullptr) const;
872
873 void HandleUseAfterFree(CheckerContext &C, SourceRange Range,
874 SymbolRef Sym) const;
875
876 void HandleDoubleFree(CheckerContext &C, SourceRange Range, bool Released,
877 SymbolRef Sym, SymbolRef PrevSym) const;
878
879 void HandleUseZeroAlloc(CheckerContext &C, SourceRange Range,
880 SymbolRef Sym) const;
881
882 void HandleFunctionPtrFree(CheckerContext &C, SVal ArgVal, SourceRange Range,
883 const Expr *FreeExpr,
884 AllocationFamily Family) const;
885
886 /// Find the location of the allocation for Sym on the path leading to the
887 /// exploded node N.
888 static LeakInfo getAllocationSite(const ExplodedNode *N, SymbolRef Sym,
889 CheckerContext &C);
890
891 void HandleLeak(SymbolRef Sym, ExplodedNode *N, CheckerContext &C) const;
892
893 /// Test if value in ArgVal equals to value in macro `ZERO_SIZE_PTR`.
894 bool isArgZERO_SIZE_PTR(ProgramStateRef State, CheckerContext &C,
895 SVal ArgVal) const;
896};
897} // end anonymous namespace
898
899//===----------------------------------------------------------------------===//
900// Definition of NoOwnershipChangeVisitor.
901//===----------------------------------------------------------------------===//
902
903namespace {
904class NoMemOwnershipChangeVisitor final : public NoOwnershipChangeVisitor {
905protected:
906 /// Syntactically checks whether the callee is a deallocating function. Since
907 /// we have no path-sensitive information on this call (we would need a
908 /// CallEvent instead of a CallExpr for that), its possible that a
909 /// deallocation function was called indirectly through a function pointer,
910 /// but we are not able to tell, so this is a best effort analysis.
911 /// See namespace `memory_passed_to_fn_call_free_through_fn_ptr` in
912 /// clang/test/Analysis/NewDeleteLeaks.cpp.
913 bool isFreeingCallAsWritten(const CallExpr &Call) const {
914 const auto *MallocChk = static_cast<const MallocChecker *>(&Checker);
915 if (MallocChk->FreeingMemFnMap.lookupAsWritten(Call) ||
916 MallocChk->ReallocatingMemFnMap.lookupAsWritten(Call))
917 return true;
918
919 if (const auto *Func =
920 llvm::dyn_cast_or_null<FunctionDecl>(Call.getCalleeDecl()))
921 return MallocChecker::isFreeingOwnershipAttrCall(Func);
922
923 return false;
924 }
925
926 bool hasResourceStateChanged(ProgramStateRef CallEnterState,
927 ProgramStateRef CallExitEndState) final {
928 return CallEnterState->get<RegionState>(Sym) !=
929 CallExitEndState->get<RegionState>(Sym);
930 }
931
932 /// Heuristically guess whether the callee intended to free memory. This is
933 /// done syntactically, because we are trying to argue about alternative
934 /// paths of execution, and as a consequence we don't have path-sensitive
935 /// information.
936 bool doesFnIntendToHandleOwnership(const Decl *Callee,
937 ASTContext &ACtx) final {
938 const FunctionDecl *FD = dyn_cast<FunctionDecl>(Callee);
939
940 // Given that the stack frame was entered, the body should always be
941 // theoretically obtainable. In case of body farms, the synthesized body
942 // is not attached to declaration, thus triggering the '!FD->hasBody()'
943 // branch. That said, would a synthesized body ever intend to handle
944 // ownership? As of today they don't. And if they did, how would we
945 // put notes inside it, given that it doesn't match any source locations?
946 if (!FD)
947 return false;
948
949 Stmt *Body = FD->getBody();
950 if (!Body)
951 return false;
952
953 using namespace clang::ast_matchers;
954
955 auto Matches = match(findAll(stmt(anyOf(cxxDeleteExpr().bind("delete"),
956 callExpr().bind("call")))),
957 *Body, ACtx);
958 for (BoundNodes Match : Matches) {
959 if (Match.getNodeAs<CXXDeleteExpr>("delete"))
960 return true;
961
962 if (const auto *Call = Match.getNodeAs<CallExpr>("call"))
963 if (isFreeingCallAsWritten(*Call))
964 return true;
965 }
966 // TODO: Ownership might change with an attempt to store the allocated
967 // memory, not only through deallocation. Check for attempted stores as
968 // well.
969 return false;
970 }
971
972 PathDiagnosticPieceRef emitNote(const ExplodedNode *N) final {
973 PathDiagnosticLocation L = PathDiagnosticLocation::create(
974 N->getLocation(),
975 N->getState()->getStateManager().getContext().getSourceManager());
976 return std::make_shared<PathDiagnosticEventPiece>(
977 L, "Returning without deallocating memory or storing the pointer for "
978 "later deallocation");
979 }
980
981public:
982 NoMemOwnershipChangeVisitor(SymbolRef Sym, const MallocChecker *Checker)
983 : NoOwnershipChangeVisitor(Sym, Checker) {}
984
985 void Profile(llvm::FoldingSetNodeID &ID) const override {
986 static int Tag = 0;
987 ID.AddPointer(&Tag);
988 ID.AddPointer(Sym);
989 }
990};
991
992} // end anonymous namespace
993
994//===----------------------------------------------------------------------===//
995// Definition of MallocBugVisitor.
996//===----------------------------------------------------------------------===//
997
998namespace {
999/// The bug visitor which allows us to print extra diagnostics along the
1000/// BugReport path. For example, showing the allocation site of the leaked
1001/// region.
1002class MallocBugVisitor final : public BugReporterVisitor {
1003protected:
1004 enum NotificationMode { Normal, ReallocationFailed };
1005
1006 // The allocated region symbol tracked by the main analysis.
1007 SymbolRef Sym;
1008
1009 // The mode we are in, i.e. what kind of diagnostics will be emitted.
1010 NotificationMode Mode;
1011
1012 // A symbol from when the primary region should have been reallocated.
1013 SymbolRef FailedReallocSymbol;
1014
1015 // A release function stack frame in which memory was released. Used for
1016 // miscellaneous false positive suppression.
1017 const StackFrame *ReleaseFunctionSF;
1018
1019 bool IsLeak;
1020
1021public:
1022 MallocBugVisitor(SymbolRef S, bool isLeak = false)
1023 : Sym(S), Mode(Normal), FailedReallocSymbol(nullptr),
1024 ReleaseFunctionSF(nullptr), IsLeak(isLeak) {}
1025
1026 static void *getTag() {
1027 static int Tag = 0;
1028 return &Tag;
1029 }
1030
1031 void Profile(llvm::FoldingSetNodeID &ID) const override {
1032 ID.AddPointer(getTag());
1033 ID.AddPointer(Sym);
1034 }
1035
1036 /// Did not track -> allocated. Other state (released) -> allocated.
1037 static inline bool isAllocated(const RefState *RSCurr, const RefState *RSPrev,
1038 const Stmt *Stmt) {
1039 return (isa_and_nonnull<CallExpr, CXXNewExpr>(Stmt) &&
1040 (RSCurr && RSCurr->isAllocated())) &&
1041 (!RSPrev || !RSPrev->isAllocated());
1042 }
1043
1044 /// Did not track -> released. Other state (allocated) -> released.
1045 /// The statement associated with the release might be missing.
1046 static inline bool isReleased(const RefState *RSCurr, const RefState *RSPrev,
1047 const Stmt *Stmt) {
1048 bool IsReleased =
1049 (RSCurr && RSCurr->isReleased()) && (!RSPrev || !RSPrev->isReleased());
1050 assert(!IsReleased || (isa_and_nonnull<CallExpr, CXXDeleteExpr>(Stmt)) ||
1051 (!Stmt && RSCurr->getAllocationFamily().Kind == AF_InnerBuffer));
1052 return IsReleased;
1053 }
1054
1055 /// Did not track -> relinquished. Other state (allocated) -> relinquished.
1056 static inline bool isRelinquished(const RefState *RSCurr,
1057 const RefState *RSPrev, const Stmt *Stmt) {
1058 return (
1059 isa_and_nonnull<CallExpr, ObjCMessageExpr, ObjCPropertyRefExpr>(Stmt) &&
1060 (RSCurr && RSCurr->isRelinquished()) &&
1061 (!RSPrev || !RSPrev->isRelinquished()));
1062 }
1063
1064 /// If the expression is not a call, and the state change is
1065 /// released -> allocated, it must be the realloc return value
1066 /// check. If we have to handle more cases here, it might be cleaner just
1067 /// to track this extra bit in the state itself.
1068 static inline bool hasReallocFailed(const RefState *RSCurr,
1069 const RefState *RSPrev,
1070 const Stmt *Stmt) {
1071 return ((!isa_and_nonnull<CallExpr>(Stmt)) &&
1072 (RSCurr && RSCurr->isAllocated())) &&
1073 (RSPrev && !RSPrev->isAllocated());
1074 }
1075
1076 PathDiagnosticPieceRef VisitNode(const ExplodedNode *N,
1077 BugReporterContext &BRC,
1078 PathSensitiveBugReport &BR) override;
1079
1080 PathDiagnosticPieceRef getEndPath(const ExplodedNode *EndPathNode,
1081 BugReporterContext &BRC,
1082 PathSensitiveBugReport &BR) override {
1083 if (!IsLeak)
1084 return nullptr;
1085
1086 PathDiagnosticLocation L = BR.getLocation();
1087 // Do not add the statement itself as a range in case of leak.
1088 return std::make_shared<PathDiagnosticEventPiece>(L, BR.getDescription(),
1089 false);
1090 }
1091
1092private:
1093 class StackHintGeneratorForReallocationFailed
1094 : public StackHintGeneratorForSymbol {
1095 public:
1096 StackHintGeneratorForReallocationFailed(SymbolRef S, StringRef M)
1097 : StackHintGeneratorForSymbol(S, M) {}
1098
1099 std::string getMessageForArg(const Expr *ArgE, unsigned ArgIndex) override {
1100 // Printed parameters start at 1, not 0.
1101 ++ArgIndex;
1102
1103 SmallString<200> buf;
1104 llvm::raw_svector_ostream os(buf);
1105
1106 os << "Reallocation of " << ArgIndex << llvm::getOrdinalSuffix(ArgIndex)
1107 << " parameter failed";
1108
1109 return std::string(os.str());
1110 }
1111
1112 std::string getMessageForReturn(const CallExpr *CallExpr) override {
1113 return "Reallocation of returned value failed";
1114 }
1115 };
1116};
1117} // end anonymous namespace
1118
1119// A map from the freed symbol to the symbol representing the return value of
1120// the free function.
1122
1123namespace {
1124class StopTrackingCallback final : public SymbolVisitor {
1125 ProgramStateRef state;
1126
1127public:
1128 StopTrackingCallback(ProgramStateRef st) : state(std::move(st)) {}
1129 ProgramStateRef getState() const { return state; }
1130
1131 bool VisitSymbol(SymbolRef sym) override {
1132 state = state->remove<RegionState>(sym);
1133 return true;
1134 }
1135};
1136
1137/// EscapeTrackedCallback - A SymbolVisitor that marks allocated symbols as
1138/// escaped.
1139///
1140/// This visitor is used to suppress false positive leak reports when smart
1141/// pointers are nested in temporary objects passed by value to functions. When
1142/// the analyzer can't see the destructor calls for temporary objects, it may
1143/// incorrectly report leaks for memory that will be properly freed by the smart
1144/// pointer destructors.
1145///
1146/// The visitor traverses reachable symbols from a given set of memory regions
1147/// (typically smart pointer field regions) and marks any allocated symbols as
1148/// escaped. Escaped symbols are not reported as leaks by checkDeadSymbols.
1149class EscapeTrackedCallback final : public SymbolVisitor {
1150 ProgramStateRef State;
1151
1152 explicit EscapeTrackedCallback(ProgramStateRef S) : State(std::move(S)) {}
1153
1154public:
1155 bool VisitSymbol(SymbolRef Sym) override {
1156 if (const RefState *RS = State->get<RegionState>(Sym)) {
1157 if (RS->isAllocated()) {
1158 State = State->set<RegionState>(Sym, RefState::getEscaped(RS));
1159 }
1160 }
1161 return true;
1162 }
1163
1164 /// Escape tracked regions reachable from the given roots.
1165 static ProgramStateRef
1166 EscapeTrackedRegionsReachableFrom(ArrayRef<const MemRegion *> Roots,
1167 ProgramStateRef State) {
1168 if (Roots.empty())
1169 return State;
1170
1171 // scanReachableSymbols is expensive, so we use a single visitor for all
1172 // roots
1173 SmallVector<const MemRegion *, 10> Regions = llvm::to_vector<10>(Roots);
1174 EscapeTrackedCallback Visitor(State);
1175 State->scanReachableSymbols(Regions, Visitor);
1176 return Visitor.State;
1177 }
1178
1179 friend class SymbolVisitor;
1180};
1181} // end anonymous namespace
1182
1183static bool isStandardNew(const FunctionDecl *FD) {
1184 if (!FD)
1185 return false;
1186
1188 if (Kind != OO_New && Kind != OO_Array_New)
1189 return false;
1190
1191 // This is standard if and only if it's not defined in a user file.
1192 SourceLocation L = FD->getLocation();
1193 // If the header for operator delete is not included, it's still defined
1194 // in an invalid source location. Check to make sure we don't crash.
1195 return !L.isValid() ||
1197}
1198
1199static bool isStandardDelete(const FunctionDecl *FD) {
1200 if (!FD)
1201 return false;
1202
1204 if (Kind != OO_Delete && Kind != OO_Array_Delete)
1205 return false;
1206
1207 bool HasBody = FD->hasBody(); // Prefer using the definition.
1208
1209 // This is standard if and only if it's not defined in a user file.
1210 SourceLocation L = FD->getLocation();
1211
1212 // If the header for operator delete is not included, it's still defined
1213 // in an invalid source location. Check to make sure we don't crash.
1214 const auto &SM = FD->getASTContext().getSourceManager();
1215 return L.isInvalid() || (!HasBody && SM.isInSystemHeader(L));
1216}
1217
1218//===----------------------------------------------------------------------===//
1219// Methods of MallocChecker and MallocBugVisitor.
1220//===----------------------------------------------------------------------===//
1221
1222bool MallocChecker::isFreeingOwnershipAttrCall(const CallEvent &Call) {
1223 const auto *Func = dyn_cast_or_null<FunctionDecl>(Call.getDecl());
1224
1225 return Func && isFreeingOwnershipAttrCall(Func);
1226}
1227
1228bool MallocChecker::isFreeingOwnershipAttrCall(const FunctionDecl *Func) {
1229 if (Func->hasAttrs()) {
1230 auto IsFreeing = [](const OwnershipAttr *I) {
1231 OwnershipAttr::OwnershipKind OwnKind = I->getOwnKind();
1232 return OwnKind == OwnershipAttr::Takes || OwnKind == OwnershipAttr::Holds;
1233 };
1234 return llvm::any_of(Func->specific_attrs<OwnershipAttr>(), IsFreeing);
1235 }
1236 return false;
1237}
1238
1239bool MallocChecker::isFreeingCall(const CallEvent &Call) const {
1240 if (FreeingMemFnMap.lookup(Call) || ReallocatingMemFnMap.lookup(Call))
1241 return true;
1242
1243 return isFreeingOwnershipAttrCall(Call);
1244}
1245
1246bool MallocChecker::isAllocatingOwnershipAttrCall(const CallEvent &Call) {
1247 const auto *Func = dyn_cast_or_null<FunctionDecl>(Call.getDecl());
1248
1249 return Func && isAllocatingOwnershipAttrCall(Func);
1250}
1251
1252bool MallocChecker::isAllocatingOwnershipAttrCall(const FunctionDecl *Func) {
1253 auto IsAllocating = [](const OwnershipAttr *I) {
1254 return I->getOwnKind() == OwnershipAttr::Returns;
1255 };
1256 return llvm::any_of(Func->specific_attrs<OwnershipAttr>(), IsAllocating);
1257}
1258
1259bool MallocChecker::isMemCall(const CallEvent &Call) const {
1260 if (FreeingMemFnMap.lookup(Call) || AllocatingMemFnMap.lookup(Call) ||
1261 AllocaMemFnMap.lookup(Call) || ReallocatingMemFnMap.lookup(Call))
1262 return true;
1263
1264 if (!ShouldIncludeOwnershipAnnotatedFunctions)
1265 return false;
1266
1267 const auto *Func = dyn_cast<FunctionDecl>(Call.getDecl());
1268 return Func && Func->hasAttr<OwnershipAttr>();
1269}
1270
1271std::optional<ProgramStateRef>
1272MallocChecker::performKernelMalloc(const CallEvent &Call, CheckerContext &C,
1273 const ProgramStateRef &State) const {
1274 // 3-argument malloc(), as commonly used in {Free,Net,Open}BSD Kernels:
1275 //
1276 // void *malloc(unsigned long size, struct malloc_type *mtp, int flags);
1277 //
1278 // One of the possible flags is M_ZERO, which means 'give me back an
1279 // allocation which is already zeroed', like calloc.
1280
1281 // 2-argument kmalloc(), as used in the Linux kernel:
1282 //
1283 // void *kmalloc(size_t size, gfp_t flags);
1284 //
1285 // Has the similar flag value __GFP_ZERO.
1286
1287 // This logic is largely cloned from O_CREAT in UnixAPIChecker, maybe some
1288 // code could be shared.
1289
1290 ASTContext &Ctx = C.getASTContext();
1291 llvm::Triple::OSType OS = Ctx.getTargetInfo().getTriple().getOS();
1292
1293 if (!KernelZeroFlagVal) {
1294 switch (OS) {
1295 case llvm::Triple::FreeBSD:
1296 KernelZeroFlagVal = 0x0100;
1297 break;
1298 case llvm::Triple::NetBSD:
1299 KernelZeroFlagVal = 0x0002;
1300 break;
1301 case llvm::Triple::OpenBSD:
1302 KernelZeroFlagVal = 0x0008;
1303 break;
1304 case llvm::Triple::Linux:
1305 // __GFP_ZERO
1306 KernelZeroFlagVal = 0x8000;
1307 break;
1308 default:
1309 // FIXME: We need a more general way of getting the M_ZERO value.
1310 // See also: O_CREAT in UnixAPIChecker.cpp.
1311
1312 // Fall back to normal malloc behavior on platforms where we don't
1313 // know M_ZERO.
1314 return std::nullopt;
1315 }
1316 }
1317
1318 // We treat the last argument as the flags argument, and callers fall-back to
1319 // normal malloc on a None return. This works for the FreeBSD kernel malloc
1320 // as well as Linux kmalloc.
1321 if (Call.getNumArgs() < 2)
1322 return std::nullopt;
1323
1324 const Expr *FlagsEx = Call.getArgExpr(Call.getNumArgs() - 1);
1325 const SVal V = C.getSVal(FlagsEx);
1326 if (!isa<NonLoc>(V)) {
1327 // The case where 'V' can be a location can only be due to a bad header,
1328 // so in this case bail out.
1329 return std::nullopt;
1330 }
1331
1332 NonLoc Flags = V.castAs<NonLoc>();
1333 NonLoc ZeroFlag = C.getSValBuilder()
1334 .makeIntVal(*KernelZeroFlagVal, FlagsEx->getType())
1335 .castAs<NonLoc>();
1336 SVal MaskedFlagsUC = C.getSValBuilder().evalBinOpNN(State, BO_And,
1337 Flags, ZeroFlag,
1338 FlagsEx->getType());
1339 if (MaskedFlagsUC.isUnknownOrUndef())
1340 return std::nullopt;
1341 DefinedSVal MaskedFlags = MaskedFlagsUC.castAs<DefinedSVal>();
1342
1343 // Check if maskedFlags is non-zero.
1344 ProgramStateRef TrueState, FalseState;
1345 std::tie(TrueState, FalseState) = State->assume(MaskedFlags);
1346
1347 // If M_ZERO is set, treat this like calloc (initialized).
1348 if (TrueState && !FalseState) {
1349 SVal ZeroVal = C.getSValBuilder().makeZeroVal(Ctx.CharTy);
1350 return MallocMemAux(C, Call, Call.getArgExpr(0), ZeroVal, TrueState,
1351 AllocationFamily(AF_Malloc));
1352 }
1353
1354 return std::nullopt;
1355}
1356
1357SVal MallocChecker::evalMulForBufferSize(CheckerContext &C, const Expr *Blocks,
1358 const Expr *BlockBytes) {
1359 SValBuilder &SB = C.getSValBuilder();
1360 SVal BlocksVal = C.getSVal(Blocks);
1361 SVal BlockBytesVal = C.getSVal(BlockBytes);
1362 ProgramStateRef State = C.getState();
1363 SVal TotalSize = SB.evalBinOp(State, BO_Mul, BlocksVal, BlockBytesVal,
1365 return TotalSize;
1366}
1367
1368void MallocChecker::checkBasicAlloc(ProgramStateRef State,
1369 const CallEvent &Call,
1370 CheckerContext &C) const {
1371 State = MallocMemAux(C, Call, Call.getArgExpr(0), UndefinedVal(), State,
1372 AllocationFamily(AF_Malloc));
1373 State = ProcessZeroAllocCheck(C, Call, 0, State);
1374 C.addTransition(State);
1375}
1376
1377void MallocChecker::checkBasicAllocMayFail(ProgramStateRef State,
1378 const CallEvent &Call,
1379 CheckerContext &C) const {
1380 C.addTransition(FailedAlloc(C, Call, State, {0}));
1381
1382 State = MallocMemAux(C, Call, Call.getArgExpr(0), UndefinedVal(), State,
1383 AllocationFamily(AF_Malloc));
1384 State = ProcessZeroAllocCheck(C, Call, 0, State);
1385 C.addTransition(State);
1386}
1387
1388void MallocChecker::checkKernelMalloc(ProgramStateRef State,
1389 const CallEvent &Call,
1390 CheckerContext &C) const {
1391 std::optional<ProgramStateRef> MaybeState =
1392 performKernelMalloc(Call, C, State);
1393 if (MaybeState)
1394 State = *MaybeState;
1395 else
1396 State = MallocMemAux(C, Call, Call.getArgExpr(0), UndefinedVal(), State,
1397 AllocationFamily(AF_Malloc));
1398 C.addTransition(State);
1399}
1400
1401static bool isStandardRealloc(const CallEvent &Call) {
1402 const FunctionDecl *FD = dyn_cast<FunctionDecl>(Call.getDecl());
1403 assert(FD);
1404 ASTContext &AC = FD->getASTContext();
1405 return AC.hasSameType(FD->getDeclaredReturnType(), AC.VoidPtrTy) &&
1406 AC.hasSameType(FD->getParamDecl(0)->getType(), AC.VoidPtrTy) &&
1407 AC.hasSameType(FD->getParamDecl(1)->getType(), AC.getSizeType());
1408}
1409
1410static bool isGRealloc(const CallEvent &Call) {
1411 const FunctionDecl *FD = dyn_cast<FunctionDecl>(Call.getDecl());
1412 assert(FD);
1413 ASTContext &AC = FD->getASTContext();
1414
1415 return AC.hasSameType(FD->getDeclaredReturnType(), AC.VoidPtrTy) &&
1416 AC.hasSameType(FD->getParamDecl(0)->getType(), AC.VoidPtrTy) &&
1418}
1419
1420void MallocChecker::checkRealloc(ProgramStateRef State, const CallEvent &Call,
1421 CheckerContext &C,
1422 bool ShouldFreeOnFail) const {
1423 bool StandardRealloc = isStandardRealloc(Call);
1424 // Ignore calls to functions whose type does not match the expected type of
1425 // either the standard realloc or g_realloc from GLib.
1426 // FIXME: Should we perform this kind of checking consistently for each
1427 // function? If yes, then perhaps extend the `CallDescription` interface to
1428 // handle this.
1429 if (!StandardRealloc && !isGRealloc(Call))
1430 return;
1431
1432 if (StandardRealloc)
1433 C.addTransition(FailedAlloc(C, Call, State, {1}));
1434
1435 State = ReallocMemAux(C, Call, ShouldFreeOnFail, State,
1436 AllocationFamily(AF_Malloc));
1437 State = ProcessZeroAllocCheck(C, Call, 1, State);
1438 C.addTransition(State);
1439}
1440
1441void MallocChecker::checkCalloc(ProgramStateRef State, const CallEvent &Call,
1442 CheckerContext &C) const {
1443 C.addTransition(FailedAlloc(C, Call, State, {0, 1}));
1444
1445 State = CallocMem(C, Call, State);
1446 State = ProcessZeroAllocCheck(C, Call, 0, State);
1447 State = ProcessZeroAllocCheck(C, Call, 1, State);
1448 C.addTransition(State);
1449}
1450
1451void MallocChecker::checkFree(ProgramStateRef State, const CallEvent &Call,
1452 CheckerContext &C) const {
1453 bool IsKnownToBeAllocatedMemory = false;
1454 if (suppressDeallocationsInSuspiciousContexts(Call, C))
1455 return;
1456 State = FreeMemAux(C, Call, State, 0, false, IsKnownToBeAllocatedMemory,
1457 AllocationFamily(AF_Malloc));
1458 C.addTransition(State);
1459}
1460
1461void MallocChecker::checkAlloca(ProgramStateRef State, const CallEvent &Call,
1462 CheckerContext &C) const {
1463 State = MallocMemAux(C, Call, Call.getArgExpr(0), UndefinedVal(), State,
1464 AllocationFamily(AF_Alloca));
1465 State = ProcessZeroAllocCheck(C, Call, 0, State);
1466 C.addTransition(State);
1467}
1468
1469void MallocChecker::checkStrdup(ProgramStateRef State, const CallEvent &Call,
1470 CheckerContext &C) const {
1471 const auto *CE = dyn_cast_or_null<CallExpr>(Call.getOriginExpr());
1472 if (!CE)
1473 return;
1474
1475 C.addTransition(FailedAlloc(C, Call, State));
1476
1477 State = MallocMemAux(C, Call, UnknownVal(), UnknownVal(), State,
1478 AllocationFamily(AF_Malloc));
1479 C.addTransition(State);
1480}
1481
1482void MallocChecker::checkIfNameIndex(ProgramStateRef State,
1483 const CallEvent &Call,
1484 CheckerContext &C) const {
1485 C.addTransition(FailedAlloc(C, Call, State));
1486
1487 // Should we model this differently? We can allocate a fixed number of
1488 // elements with zeros in the last one.
1489 State = MallocMemAux(C, Call, UnknownVal(), UnknownVal(), State,
1490 AllocationFamily(AF_IfNameIndex));
1491 C.addTransition(State);
1492}
1493
1494void MallocChecker::checkIfFreeNameIndex(ProgramStateRef State,
1495 const CallEvent &Call,
1496 CheckerContext &C) const {
1497 bool IsKnownToBeAllocatedMemory = false;
1498 State = FreeMemAux(C, Call, State, 0, false, IsKnownToBeAllocatedMemory,
1499 AllocationFamily(AF_IfNameIndex));
1500 C.addTransition(State);
1501}
1502
1504 const FunctionDecl *FD) {
1505 // Checking for signature:
1506 // void* operator new ( std::size_t count, void* ptr );
1507 // void* operator new[]( std::size_t count, void* ptr );
1508 if (CE->getNumArgs() != 2 || (FD->getOverloadedOperator() != OO_New &&
1509 FD->getOverloadedOperator() != OO_Array_New))
1510 return nullptr;
1511 auto BuffType = FD->getParamDecl(1)->getType();
1512 if (BuffType.isNull() || !BuffType->isVoidPointerType())
1513 return nullptr;
1514 return CE->getArg(1);
1515}
1516
1517void MallocChecker::checkCXXNewOrCXXDelete(ProgramStateRef State,
1518 const CallEvent &Call,
1519 CheckerContext &C) const {
1520 bool IsKnownToBeAllocatedMemory = false;
1521 const auto *CE = dyn_cast_or_null<CallExpr>(Call.getOriginExpr());
1522 if (!CE)
1523 return;
1524
1525 assert(isStandardNewDelete(Call));
1526
1527 // Process direct calls to operator new/new[]/delete/delete[] functions
1528 // as distinct from new/new[]/delete/delete[] expressions that are
1529 // processed by the checkPostStmt callbacks for CXXNewExpr and
1530 // CXXDeleteExpr.
1531 const FunctionDecl *FD = C.getCalleeDecl(CE);
1532 if (const auto *BufArg = getPlacementNewBufferArg(CE, FD)) {
1533 // Placement new does not allocate memory
1534 auto RetVal = State->getSVal(BufArg, Call.getStackFrame());
1535 State = State->BindExpr(CE, C.getStackFrame(), RetVal);
1536 C.addTransition(State);
1537 return;
1538 }
1539
1540 switch (FD->getOverloadedOperator()) {
1541 case OO_New:
1542 State = MallocMemAux(C, Call, CE->getArg(0), UndefinedVal(), State,
1543 AllocationFamily(AF_CXXNew));
1544 State = ProcessZeroAllocCheck(C, Call, 0, State);
1545 break;
1546 case OO_Array_New:
1547 State = MallocMemAux(C, Call, CE->getArg(0), UndefinedVal(), State,
1548 AllocationFamily(AF_CXXNewArray));
1549 State = ProcessZeroAllocCheck(C, Call, 0, State);
1550 break;
1551 case OO_Delete:
1552 State = FreeMemAux(C, Call, State, 0, false, IsKnownToBeAllocatedMemory,
1553 AllocationFamily(AF_CXXNew));
1554 break;
1555 case OO_Array_Delete:
1556 State = FreeMemAux(C, Call, State, 0, false, IsKnownToBeAllocatedMemory,
1557 AllocationFamily(AF_CXXNewArray));
1558 break;
1559 default:
1560 assert(false && "not a new/delete operator");
1561 return;
1562 }
1563
1564 C.addTransition(State);
1565}
1566
1567void MallocChecker::checkGMalloc0(ProgramStateRef State, const CallEvent &Call,
1568 CheckerContext &C) const {
1569 SValBuilder &svalBuilder = C.getSValBuilder();
1570 SVal zeroVal = svalBuilder.makeZeroVal(svalBuilder.getContext().CharTy);
1571 State = MallocMemAux(C, Call, Call.getArgExpr(0), zeroVal, State,
1572 AllocationFamily(AF_Malloc));
1573 State = ProcessZeroAllocCheck(C, Call, 0, State);
1574 C.addTransition(State);
1575}
1576
1577void MallocChecker::checkGMemdup(ProgramStateRef State, const CallEvent &Call,
1578 CheckerContext &C) const {
1579 State = MallocMemAux(C, Call, Call.getArgExpr(1), UnknownVal(), State,
1580 AllocationFamily(AF_Malloc));
1581 State = ProcessZeroAllocCheck(C, Call, 1, State);
1582 C.addTransition(State);
1583}
1584
1585void MallocChecker::checkGMallocN(ProgramStateRef State, const CallEvent &Call,
1586 CheckerContext &C) const {
1587 SVal Init = UndefinedVal();
1588 SVal TotalSize = evalMulForBufferSize(C, Call.getArgExpr(0), Call.getArgExpr(1));
1589 State = MallocMemAux(C, Call, TotalSize, Init, State,
1590 AllocationFamily(AF_Malloc));
1591 State = ProcessZeroAllocCheck(C, Call, 0, State);
1592 State = ProcessZeroAllocCheck(C, Call, 1, State);
1593 C.addTransition(State);
1594}
1595
1596void MallocChecker::checkGMallocN0(ProgramStateRef State, const CallEvent &Call,
1597 CheckerContext &C) const {
1598 SValBuilder &SB = C.getSValBuilder();
1599 SVal Init = SB.makeZeroVal(SB.getContext().CharTy);
1600 SVal TotalSize = evalMulForBufferSize(C, Call.getArgExpr(0), Call.getArgExpr(1));
1601 State = MallocMemAux(C, Call, TotalSize, Init, State,
1602 AllocationFamily(AF_Malloc));
1603 State = ProcessZeroAllocCheck(C, Call, 0, State);
1604 State = ProcessZeroAllocCheck(C, Call, 1, State);
1605 C.addTransition(State);
1606}
1607
1608static bool isFromStdNamespace(const CallEvent &Call) {
1609 const Decl *FD = Call.getDecl();
1610 assert(FD && "a CallDescription cannot match a call without a Decl");
1611 return FD->isInStdNamespace();
1612}
1613
1614void MallocChecker::preGetDelimOrGetLine(ProgramStateRef State,
1615 const CallEvent &Call,
1616 CheckerContext &C) const {
1617 // Discard calls to the C++ standard library function std::getline(), which
1618 // is completely unrelated to the POSIX getline() that we're checking.
1620 return;
1621
1622 const auto LinePtr = getPointeeVal(Call.getArgSVal(0), State);
1623 if (!LinePtr)
1624 return;
1625
1626 // FreeMemAux takes IsKnownToBeAllocated as an output parameter, and it will
1627 // be true after the call if the symbol was registered by this checker.
1628 // We do not need this value here, as FreeMemAux will take care
1629 // of reporting any violation of the preconditions.
1630 bool IsKnownToBeAllocated = false;
1631 State = FreeMemAux(C, Call.getArgExpr(0), Call, State, false,
1632 IsKnownToBeAllocated, AllocationFamily(AF_Malloc), false,
1633 LinePtr);
1634 if (State)
1635 C.addTransition(State);
1636}
1637
1638void MallocChecker::checkGetDelimOrGetLine(ProgramStateRef State,
1639 const CallEvent &Call,
1640 CheckerContext &C) const {
1641 // Discard calls to the C++ standard library function std::getline(), which
1642 // is completely unrelated to the POSIX getline() that we're checking.
1644 return;
1645
1646 // Handle the post-conditions of getline and getdelim:
1647 // Register the new conjured value as an allocated buffer.
1648 const CallExpr *CE = dyn_cast_or_null<CallExpr>(Call.getOriginExpr());
1649 if (!CE)
1650 return;
1651
1652 const auto LinePtrOpt = getPointeeVal(Call.getArgSVal(0), State);
1653 const auto SizeOpt = getPointeeVal(Call.getArgSVal(1), State);
1654 if (!LinePtrOpt || !SizeOpt || LinePtrOpt->isUnknownOrUndef() ||
1655 SizeOpt->isUnknownOrUndef())
1656 return;
1657
1658 const auto LinePtr = LinePtrOpt->getAs<DefinedSVal>();
1659 const auto Size = SizeOpt->getAs<DefinedSVal>();
1660 const MemRegion *LinePtrReg = LinePtr->getAsRegion();
1661 if (!LinePtrReg)
1662 return;
1663
1664 State = setDynamicExtent(State, LinePtrReg, *Size);
1665 C.addTransition(MallocUpdateRefState(C, CE, State,
1666 AllocationFamily(AF_Malloc), *LinePtr));
1667}
1668
1669void MallocChecker::checkReallocN(ProgramStateRef State, const CallEvent &Call,
1670 CheckerContext &C) const {
1671 State = ReallocMemAux(C, Call, /*ShouldFreeOnFail=*/false, State,
1672 AllocationFamily(AF_Malloc),
1673 /*SuffixWithN=*/true);
1674 State = ProcessZeroAllocCheck(C, Call, 1, State);
1675 State = ProcessZeroAllocCheck(C, Call, 2, State);
1676 C.addTransition(State);
1677}
1678
1679void MallocChecker::checkOwnershipAttr(ProgramStateRef State,
1680 const CallEvent &Call,
1681 CheckerContext &C) const {
1682 const auto *CE = dyn_cast_or_null<CallExpr>(Call.getOriginExpr());
1683 if (!CE)
1684 return;
1685 const FunctionDecl *FD = C.getCalleeDecl(CE);
1686 if (!FD)
1687 return;
1688 if (ShouldIncludeOwnershipAnnotatedFunctions ||
1689 MismatchedDeallocatorChecker.isEnabled()) {
1690 // Check all the attributes, if there are any.
1691 // There can be multiple of these attributes.
1692 if (FD->hasAttrs())
1693 for (const auto *I : FD->specific_attrs<OwnershipAttr>()) {
1694 switch (I->getOwnKind()) {
1695 case OwnershipAttr::Returns:
1696 State = MallocMemReturnsAttr(C, Call, I, State);
1697 break;
1698 case OwnershipAttr::Takes:
1699 case OwnershipAttr::Holds:
1700 State = FreeMemAttr(C, Call, I, State);
1701 break;
1702 }
1703 }
1704 }
1705 C.addTransition(State);
1706}
1707
1708bool MallocChecker::evalCall(const CallEvent &Call, CheckerContext &C) const {
1709 if (!Call.getOriginExpr())
1710 return false;
1711
1712 ProgramStateRef State = C.getState();
1713
1714 if (const CheckFn *Callback = FreeingMemFnMap.lookup(Call)) {
1715 (*Callback)(this, State, Call, C);
1716 return true;
1717 }
1718
1719 if (const CheckFn *Callback = AllocatingMemFnMap.lookup(Call)) {
1720 State = MallocBindRetVal(C, Call, State, false);
1721 (*Callback)(this, State, Call, C);
1722 return true;
1723 }
1724
1725 if (const CheckFn *Callback = ReallocatingMemFnMap.lookup(Call)) {
1726 State = MallocBindRetVal(C, Call, State, false);
1727 (*Callback)(this, State, Call, C);
1728 return true;
1729 }
1730
1731 if (isStandardNew(Call)) {
1732 State = MallocBindRetVal(C, Call, State, false);
1733 checkCXXNewOrCXXDelete(State, Call, C);
1734 return true;
1735 }
1736
1737 if (isStandardDelete(Call)) {
1738 checkCXXNewOrCXXDelete(State, Call, C);
1739 return true;
1740 }
1741
1742 if (const CheckFn *Callback = AllocaMemFnMap.lookup(Call)) {
1743 State = MallocBindRetVal(C, Call, State, true);
1744 (*Callback)(this, State, Call, C);
1745 return true;
1746 }
1747
1748 if (isFreeingOwnershipAttrCall(Call) || isAllocatingOwnershipAttrCall(Call)) {
1749 if (isAllocatingOwnershipAttrCall(Call))
1750 State = MallocBindRetVal(C, Call, State, false);
1751 checkOwnershipAttr(State, Call, C);
1752 return true;
1753 }
1754
1755 return false;
1756}
1757
1758// Performs a 0-sized allocations check.
1759ProgramStateRef MallocChecker::ProcessZeroAllocCheck(
1760 CheckerContext &C, const CallEvent &Call, const unsigned IndexOfSizeArg,
1761 ProgramStateRef State, std::optional<SVal> RetVal) {
1762 if (!State)
1763 return nullptr;
1764
1765 const Expr *Arg = nullptr;
1766
1767 if (const CallExpr *CE = dyn_cast<CallExpr>(Call.getOriginExpr())) {
1768 Arg = CE->getArg(IndexOfSizeArg);
1769 } else if (const CXXNewExpr *NE =
1770 dyn_cast<CXXNewExpr>(Call.getOriginExpr())) {
1771 if (NE->isArray()) {
1772 Arg = *NE->getArraySize();
1773 } else {
1774 return State;
1775 }
1776 } else {
1777 assert(false && "not a CallExpr or CXXNewExpr");
1778 return nullptr;
1779 }
1780
1781 if (!RetVal)
1782 RetVal = State->getSVal(Call.getOriginExpr(), C.getStackFrame());
1783
1784 assert(Arg);
1785
1786 auto DefArgVal =
1787 State->getSVal(Arg, Call.getStackFrame()).getAs<DefinedSVal>();
1788
1789 if (!DefArgVal)
1790 return State;
1791
1792 // Check if the allocation size is 0.
1793 ProgramStateRef TrueState, FalseState;
1794 SValBuilder &SvalBuilder = State->getStateManager().getSValBuilder();
1795 DefinedSVal Zero =
1796 SvalBuilder.makeZeroVal(Arg->getType()).castAs<DefinedSVal>();
1797
1798 std::tie(TrueState, FalseState) =
1799 State->assume(SvalBuilder.evalEQ(State, *DefArgVal, Zero));
1800
1801 if (TrueState && !FalseState) {
1802 SymbolRef Sym = RetVal->getAsLocSymbol();
1803 if (!Sym)
1804 return State;
1805
1806 const RefState *RS = State->get<RegionState>(Sym);
1807 if (RS) {
1808 if (RS->isAllocated() && !RS->isAllocatedOfSizeZero())
1809 return TrueState->set<RegionState>(
1810 Sym, RefState::getAllocatedOfSizeZero(RS));
1811 return State;
1812 }
1813 // Case of zero-size realloc. Historically 'realloc(ptr, 0)' is treated as
1814 // 'free(ptr)' and the returned value from 'realloc(ptr, 0)' is not
1815 // tracked. Add zero-reallocated Sym to the state to catch references
1816 // to zero-allocated memory.
1817 return TrueState->add<ReallocSizeZeroSymbols>(Sym);
1818 }
1819
1820 // Assume the value is non-zero going forward.
1821 assert(FalseState);
1822 return FalseState;
1823}
1824
1826 QualType Result = T, PointeeType = T->getPointeeType();
1827 while (!PointeeType.isNull()) {
1828 Result = PointeeType;
1829 PointeeType = PointeeType->getPointeeType();
1830 }
1831 return Result;
1832}
1833
1834/// \returns true if the constructor invoked by \p NE has an argument of a
1835/// pointer/reference to a record type.
1837
1838 const CXXConstructExpr *ConstructE = NE->getConstructExpr();
1839 if (!ConstructE)
1840 return false;
1841
1842 if (!NE->getAllocatedType()->getAsCXXRecordDecl())
1843 return false;
1844
1845 const CXXConstructorDecl *CtorD = ConstructE->getConstructor();
1846
1847 // Iterate over the constructor parameters.
1848 for (const auto *CtorParam : CtorD->parameters()) {
1849
1850 QualType CtorParamPointeeT = CtorParam->getType()->getPointeeType();
1851 if (CtorParamPointeeT.isNull())
1852 continue;
1853
1854 CtorParamPointeeT = getDeepPointeeType(CtorParamPointeeT);
1855
1856 if (CtorParamPointeeT->getAsCXXRecordDecl())
1857 return true;
1858 }
1859
1860 return false;
1861}
1862
1864MallocChecker::processNewAllocation(const CXXAllocatorCall &Call,
1865 CheckerContext &C,
1866 AllocationFamily Family) const {
1868 return nullptr;
1869
1870 const CXXNewExpr *NE = Call.getOriginExpr();
1871 const ParentMap &PM = C.getStackFrame()->getParentMap();
1872 ProgramStateRef State = C.getState();
1873
1874 // Non-trivial constructors have a chance to escape 'this', but marking all
1875 // invocations of trivial constructors as escaped would cause too great of
1876 // reduction of true positives, so let's just do that for constructors that
1877 // have an argument of a pointer-to-record type.
1879 return State;
1880
1881 // The return value from operator new is bound to a specified initialization
1882 // value (if any) and we don't want to loose this value. So we call
1883 // MallocUpdateRefState() instead of MallocMemAux() which breaks the
1884 // existing binding.
1885 SVal Target = Call.getObjectUnderConstruction();
1886 if (Call.getOriginExpr()->isArray()) {
1887 if (auto SizeEx = NE->getArraySize())
1888 checkTaintedness(C, Call, C.getSVal(*SizeEx), State,
1889 AllocationFamily(AF_CXXNewArray));
1890 }
1891
1892 State = MallocUpdateRefState(C, NE, State, Family, Target);
1893 State = ProcessZeroAllocCheck(C, Call, 0, State, Target);
1894 return State;
1895}
1896
1897void MallocChecker::checkNewAllocator(const CXXAllocatorCall &Call,
1898 CheckerContext &C) const {
1899 if (!C.wasInlined) {
1900 ProgramStateRef State = processNewAllocation(
1901 Call, C,
1902 AllocationFamily(Call.getOriginExpr()->isArray() ? AF_CXXNewArray
1903 : AF_CXXNew));
1904 C.addTransition(State);
1905 }
1906}
1907
1909 // If the first selector piece is one of the names below, assume that the
1910 // object takes ownership of the memory, promising to eventually deallocate it
1911 // with free().
1912 // Ex: [NSData dataWithBytesNoCopy:bytes length:10];
1913 // (...unless a 'freeWhenDone' parameter is false, but that's checked later.)
1914 StringRef FirstSlot = Call.getSelector().getNameForSlot(0);
1915 return FirstSlot == "dataWithBytesNoCopy" ||
1916 FirstSlot == "initWithBytesNoCopy" ||
1917 FirstSlot == "initWithCharactersNoCopy";
1918}
1919
1920static std::optional<bool> getFreeWhenDoneArg(const ObjCMethodCall &Call) {
1921 Selector S = Call.getSelector();
1922
1923 // FIXME: We should not rely on fully-constrained symbols being folded.
1924 for (unsigned i = 1; i < S.getNumArgs(); ++i)
1925 if (S.getNameForSlot(i) == "freeWhenDone")
1926 return !Call.getArgSVal(i).isZeroConstant();
1927
1928 return std::nullopt;
1929}
1930
1931void MallocChecker::checkPostObjCMessage(const ObjCMethodCall &Call,
1932 CheckerContext &C) const {
1933 if (C.wasInlined)
1934 return;
1935
1937 return;
1938
1939 if (std::optional<bool> FreeWhenDone = getFreeWhenDoneArg(Call))
1940 if (!*FreeWhenDone)
1941 return;
1942
1943 if (Call.hasNonZeroCallbackArg())
1944 return;
1945
1946 bool IsKnownToBeAllocatedMemory;
1947 ProgramStateRef State = FreeMemAux(C, Call.getArgExpr(0), Call, C.getState(),
1948 /*Hold=*/true, IsKnownToBeAllocatedMemory,
1949 AllocationFamily(AF_Malloc),
1950 /*ReturnsNullOnFailure=*/true);
1951
1952 C.addTransition(State);
1953}
1954
1956MallocChecker::MallocMemReturnsAttr(CheckerContext &C, const CallEvent &Call,
1957 const OwnershipAttr *Att,
1958 ProgramStateRef State) const {
1959 if (!State)
1960 return nullptr;
1961
1962 auto attrClassName = Att->getModule()->getName();
1963 auto Family = AllocationFamily(AF_Custom, attrClassName);
1964
1965 if (!Att->args().empty()) {
1966 return MallocMemAux(C, Call,
1967 Call.getArgExpr(Att->args_begin()->getASTIndex()),
1968 UnknownVal(), State, Family);
1969 }
1970 return MallocMemAux(C, Call, UnknownVal(), UnknownVal(), State, Family);
1971}
1972
1973ProgramStateRef MallocChecker::MallocBindRetVal(CheckerContext &C,
1974 const CallEvent &Call,
1975 ProgramStateRef State,
1976 bool isAlloca) const {
1977 const Expr *CE = Call.getOriginExpr();
1978
1979 // We expect the allocation functions to return a pointer.
1980 if (!Loc::isLocType(CE->getType()))
1981 return nullptr;
1982
1983 unsigned Count = C.blockCount();
1984 SValBuilder &SVB = C.getSValBuilder();
1985 const StackFrame *SF = C.getPredecessor()->getStackFrame();
1986 DefinedSVal RetVal =
1987 isAlloca ? SVB.getAllocaRegionVal(CE, SF, Count)
1988 : SVB.getConjuredHeapSymbolVal(Call.getCFGElementRef(), SF,
1989 CE->getType(), Count);
1990 return State->BindExpr(CE, C.getStackFrame(), RetVal);
1991}
1992
1993ProgramStateRef MallocChecker::MallocMemAux(CheckerContext &C,
1994 const CallEvent &Call,
1995 const Expr *SizeEx, SVal Init,
1996 ProgramStateRef State,
1997 AllocationFamily Family) const {
1998 if (!State)
1999 return nullptr;
2000
2001 assert(SizeEx);
2002 return MallocMemAux(C, Call, C.getSVal(SizeEx), Init, State, Family);
2003}
2004
2005void MallocChecker::reportTaintBug(StringRef Msg, ProgramStateRef State,
2006 CheckerContext &C,
2007 llvm::ArrayRef<SymbolRef> TaintedSyms,
2008 AllocationFamily Family) const {
2009 if (ExplodedNode *N = C.generateNonFatalErrorNode(State, this)) {
2010 auto R =
2011 std::make_unique<PathSensitiveBugReport>(TaintedAllocChecker, Msg, N);
2012 for (const auto *TaintedSym : TaintedSyms) {
2013 R->markInteresting(TaintedSym);
2014 }
2015 C.emitReport(std::move(R));
2016 }
2017}
2018
2019void MallocChecker::checkTaintedness(CheckerContext &C, const CallEvent &Call,
2020 const SVal SizeSVal, ProgramStateRef State,
2021 AllocationFamily Family) const {
2022 if (!TaintedAllocChecker.isEnabled())
2023 return;
2024 std::vector<SymbolRef> TaintedSyms =
2025 taint::getTaintedSymbols(State, SizeSVal);
2026 if (TaintedSyms.empty())
2027 return;
2028
2029 SValBuilder &SVB = C.getSValBuilder();
2030 QualType SizeTy = SVB.getContext().getSizeType();
2031 QualType CmpTy = SVB.getConditionType();
2032 // In case the symbol is tainted, we give a warning if the
2033 // size is larger than SIZE_MAX/4
2034 BasicValueFactory &BVF = SVB.getBasicValueFactory();
2035 const llvm::APSInt MaxValInt = BVF.getMaxValue(SizeTy);
2036 NonLoc MaxLength =
2037 SVB.makeIntVal(MaxValInt / APSIntType(MaxValInt).getValue(4));
2038 std::optional<NonLoc> SizeNL = SizeSVal.getAs<NonLoc>();
2039 auto Cmp = SVB.evalBinOpNN(State, BO_GE, *SizeNL, MaxLength, CmpTy)
2040 .getAs<DefinedOrUnknownSVal>();
2041 if (!Cmp)
2042 return;
2043 auto [StateTooLarge, StateNotTooLarge] = State->assume(*Cmp);
2044 if (!StateTooLarge && StateNotTooLarge) {
2045 // We can prove that size is not too large so there is no issue.
2046 return;
2047 }
2048
2049 std::string Callee = "Memory allocation function";
2050 if (Call.getCalleeIdentifier())
2051 Callee = Call.getCalleeIdentifier()->getName().str();
2052 reportTaintBug(
2053 Callee + " is called with a tainted (potentially attacker controlled) "
2054 "value; make sure the value is bound checked",
2055 State, C, TaintedSyms, Family);
2056}
2057
2058ProgramStateRef MallocChecker::MallocMemAux(CheckerContext &C,
2059 const CallEvent &Call, SVal Size,
2060 SVal Init, ProgramStateRef State,
2061 AllocationFamily Family) const {
2062 if (!State)
2063 return nullptr;
2064
2065 const Expr *CE = Call.getOriginExpr();
2066
2067 // We expect the malloc functions to return a pointer.
2068 // Should have been already checked.
2069 assert(Loc::isLocType(CE->getType()) &&
2070 "Allocation functions must return a pointer");
2071
2072 const StackFrame *SF = C.getPredecessor()->getStackFrame();
2073 SVal RetVal = State->getSVal(CE, C.getStackFrame());
2074
2075 // Fill the region with the initialization value.
2076 // FIXME: Why use stack frame of the predecessor?
2077 State = State->bindDefaultInitial(RetVal, Init, SF);
2078
2079 // If Size is somehow undefined at this point, this line prevents a crash.
2080 if (Size.isUndef())
2081 Size = UnknownVal();
2082
2083 checkTaintedness(C, Call, Size, State, AllocationFamily(AF_Malloc));
2084
2085 // Set the region's extent.
2086 State = setDynamicExtent(State, RetVal.getAsRegion(),
2087 Size.castAs<DefinedOrUnknownSVal>());
2088
2089 return MallocUpdateRefState(C, CE, State, Family);
2090}
2091
2093MallocChecker::FailedAlloc(CheckerContext &C, const CallEvent &Call,
2094 ProgramStateRef State,
2095 llvm::ArrayRef<unsigned> SizeArgIndexes) const {
2096 if (!State || !ModelAllocationFailure)
2097 return nullptr;
2098
2099 for (unsigned SizeArgI : SizeArgIndexes) {
2100 auto DefArgVal = Call.getArgSVal(SizeArgI).getAs<DefinedOrUnknownSVal>();
2101 if (!DefArgVal)
2102 return nullptr;
2103 State = State->assume(*DefArgVal, true);
2104 if (!State)
2105 return nullptr;
2106 }
2107
2108 auto RetVal = State->getSVal(Call.getOriginExpr(), C.getStackFrame())
2109 .castAs<DefinedOrUnknownSVal>();
2110 return State->assume(RetVal, false);
2111}
2112
2114 ProgramStateRef State,
2115 AllocationFamily Family,
2116 std::optional<SVal> RetVal) {
2117 if (!State)
2118 return nullptr;
2119
2120 // Get the return value.
2121 if (!RetVal)
2122 RetVal = State->getSVal(E, C.getStackFrame());
2123
2124 // We expect the malloc functions to return a pointer.
2125 if (!RetVal->getAs<Loc>())
2126 return nullptr;
2127
2128 SymbolRef Sym = RetVal->getAsLocSymbol();
2129
2130 // NOTE: If this was an `alloca()` call, then `RetVal` holds an
2131 // `AllocaRegion`, so `Sym` will be a nullpointer because `AllocaRegion`s do
2132 // not have an associated symbol. However, this distinct region type means
2133 // that we don't need to store anything about them in `RegionState`.
2134
2135 if (Sym)
2136 return State->set<RegionState>(Sym, RefState::getAllocated(Family, E));
2137
2138 return State;
2139}
2140
2141ProgramStateRef MallocChecker::FreeMemAttr(CheckerContext &C,
2142 const CallEvent &Call,
2143 const OwnershipAttr *Att,
2144 ProgramStateRef State) const {
2145 if (!State)
2146 return nullptr;
2147
2148 auto attrClassName = Att->getModule()->getName();
2149 auto Family = AllocationFamily(AF_Custom, attrClassName);
2150
2151 bool IsKnownToBeAllocated = false;
2152
2153 for (const auto &Arg : Att->args()) {
2154 ProgramStateRef StateI =
2155 FreeMemAux(C, Call, State, Arg.getASTIndex(),
2156 Att->getOwnKind() == OwnershipAttr::Holds,
2157 IsKnownToBeAllocated, Family);
2158 if (StateI)
2159 State = StateI;
2160 }
2161 return State;
2162}
2163
2164ProgramStateRef MallocChecker::FreeMemAux(CheckerContext &C,
2165 const CallEvent &Call,
2166 ProgramStateRef State, unsigned Num,
2167 bool Hold, bool &IsKnownToBeAllocated,
2168 AllocationFamily Family,
2169 bool ReturnsNullOnFailure) const {
2170 if (!State)
2171 return nullptr;
2172
2173 if (Call.getNumArgs() < (Num + 1))
2174 return nullptr;
2175
2176 return FreeMemAux(C, Call.getArgExpr(Num), Call, State, Hold,
2177 IsKnownToBeAllocated, Family, ReturnsNullOnFailure);
2178}
2179
2180/// Checks if the previous call to free on the given symbol failed - if free
2181/// failed, returns true. Also, returns the corresponding return value symbol.
2183 SymbolRef Sym, SymbolRef &RetStatusSymbol) {
2184 const SymbolRef *Ret = State->get<FreeReturnValue>(Sym);
2185 if (Ret) {
2186 assert(*Ret && "We should not store the null return symbol");
2187 ConstraintManager &CMgr = State->getConstraintManager();
2188 ConditionTruthVal FreeFailed = CMgr.isNull(State, *Ret);
2189 RetStatusSymbol = *Ret;
2190 return FreeFailed.isConstrainedTrue();
2191 }
2192 return false;
2193}
2194
2195static void printOwnershipTakesList(raw_ostream &os, CheckerContext &C,
2196 const Expr *E) {
2197 const CallExpr *CE = dyn_cast<CallExpr>(E);
2198
2199 if (!CE)
2200 return;
2201
2202 const FunctionDecl *FD = CE->getDirectCallee();
2203 if (!FD)
2204 return;
2205
2206 // Only one ownership_takes attribute is allowed.
2207 for (const auto *I : FD->specific_attrs<OwnershipAttr>()) {
2208 if (I->getOwnKind() != OwnershipAttr::Takes)
2209 continue;
2210
2211 os << ", which takes ownership of '" << I->getModule()->getName() << '\'';
2212 break;
2213 }
2214}
2215
2216static bool printMemFnName(raw_ostream &os, CheckerContext &C, const Expr *E) {
2217 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
2218 // FIXME: This doesn't handle indirect calls.
2219 const FunctionDecl *FD = CE->getDirectCallee();
2220 if (!FD)
2221 return false;
2222
2223 os << '\'' << *FD;
2224
2225 if (!FD->isOverloadedOperator())
2226 os << "()";
2227
2228 os << '\'';
2229 return true;
2230 }
2231
2232 if (const ObjCMessageExpr *Msg = dyn_cast<ObjCMessageExpr>(E)) {
2233 if (Msg->isInstanceMessage())
2234 os << "-";
2235 else
2236 os << "+";
2237 Msg->getSelector().print(os);
2238 return true;
2239 }
2240
2241 if (const CXXNewExpr *NE = dyn_cast<CXXNewExpr>(E)) {
2242 os << "'"
2243 << getOperatorSpelling(NE->getOperatorNew()->getOverloadedOperator())
2244 << "'";
2245 return true;
2246 }
2247
2248 if (const CXXDeleteExpr *DE = dyn_cast<CXXDeleteExpr>(E)) {
2249 os << "'"
2250 << getOperatorSpelling(DE->getOperatorDelete()->getOverloadedOperator())
2251 << "'";
2252 return true;
2253 }
2254
2255 return false;
2256}
2257
2258static void printExpectedAllocName(raw_ostream &os, AllocationFamily Family) {
2259
2260 switch (Family.Kind) {
2261 case AF_Malloc:
2262 os << "'malloc()'";
2263 return;
2264 case AF_CXXNew:
2265 os << "'new'";
2266 return;
2267 case AF_CXXNewArray:
2268 os << "'new[]'";
2269 return;
2270 case AF_IfNameIndex:
2271 os << "'if_nameindex()'";
2272 return;
2273 case AF_InnerBuffer:
2274 os << "container-specific allocator";
2275 return;
2276 case AF_Custom:
2277 os << Family.CustomName.value();
2278 return;
2279 case AF_Alloca:
2280 case AF_None:
2281 assert(false && "not a deallocation expression");
2282 }
2283}
2284
2285static void printExpectedDeallocName(raw_ostream &os, AllocationFamily Family) {
2286 switch (Family.Kind) {
2287 case AF_Malloc:
2288 os << "'free()'";
2289 return;
2290 case AF_CXXNew:
2291 os << "'delete'";
2292 return;
2293 case AF_CXXNewArray:
2294 os << "'delete[]'";
2295 return;
2296 case AF_IfNameIndex:
2297 os << "'if_freenameindex()'";
2298 return;
2299 case AF_InnerBuffer:
2300 os << "container-specific deallocator";
2301 return;
2302 case AF_Custom:
2303 os << "function that takes ownership of '" << Family.CustomName.value()
2304 << "\'";
2305 return;
2306 case AF_Alloca:
2307 case AF_None:
2308 assert(false && "not a deallocation expression");
2309 }
2310}
2311
2313MallocChecker::FreeMemAux(CheckerContext &C, const Expr *ArgExpr,
2314 const CallEvent &Call, ProgramStateRef State,
2315 bool Hold, bool &IsKnownToBeAllocated,
2316 AllocationFamily Family, bool ReturnsNullOnFailure,
2317 std::optional<SVal> ArgValOpt) const {
2318
2319 if (!State)
2320 return nullptr;
2321
2322 SVal ArgVal = ArgValOpt.value_or(C.getSVal(ArgExpr));
2323 if (!isa<DefinedOrUnknownSVal>(ArgVal))
2324 return nullptr;
2325 DefinedOrUnknownSVal location = ArgVal.castAs<DefinedOrUnknownSVal>();
2326
2327 // Check for null dereferences.
2328 if (!isa<Loc>(location))
2329 return nullptr;
2330
2331 // The explicit NULL case, no operation is performed.
2332 ProgramStateRef notNullState, nullState;
2333 std::tie(notNullState, nullState) = State->assume(location);
2334 if (nullState && !notNullState)
2335 return nullptr;
2336
2337 // Unknown values could easily be okay
2338 // Undefined values are handled elsewhere
2339 if (ArgVal.isUnknownOrUndef())
2340 return nullptr;
2341
2342 const MemRegion *R = ArgVal.getAsRegion();
2343 const Expr *ParentExpr = Call.getOriginExpr();
2344
2345 // NOTE: We detected a bug, but the checker under whose name we would emit the
2346 // error could be disabled. Generally speaking, the MallocChecker family is an
2347 // integral part of the Static Analyzer, and disabling any part of it should
2348 // only be done under exceptional circumstances, such as frequent false
2349 // positives. If this is the case, we can reasonably believe that there are
2350 // serious faults in our understanding of the source code, and even if we
2351 // don't emit an warning, we should terminate further analysis with a sink
2352 // node.
2353
2354 // Nonlocs can't be freed, of course.
2355 // Non-region locations (labels and fixed addresses) also shouldn't be freed.
2356 if (!R) {
2357 // Exception:
2358 // If the macro ZERO_SIZE_PTR is defined, this could be a kernel source
2359 // code. In that case, the ZERO_SIZE_PTR defines a special value used for a
2360 // zero-sized memory block which is allowed to be freed, despite not being a
2361 // null pointer.
2362 if (Family.Kind != AF_Malloc || !isArgZERO_SIZE_PTR(State, C, ArgVal))
2363 HandleNonHeapDealloc(C, ArgVal, ArgExpr->getSourceRange(), ParentExpr,
2364 Family);
2365 return nullptr;
2366 }
2367
2368 R = R->StripCasts();
2369
2370 // Blocks might show up as heap data, but should not be free()d
2371 if (isa<BlockDataRegion>(R)) {
2372 HandleNonHeapDealloc(C, ArgVal, ArgExpr->getSourceRange(), ParentExpr,
2373 Family);
2374 return nullptr;
2375 }
2376
2377 // Parameters, locals, statics, globals, and memory returned by
2378 // __builtin_alloca() shouldn't be freed.
2379 if (!R->hasMemorySpace<UnknownSpaceRegion, HeapSpaceRegion>(State)) {
2380 // Regions returned by malloc() are represented by SymbolicRegion objects
2381 // within HeapSpaceRegion. Of course, free() can work on memory allocated
2382 // outside the current function, so UnknownSpaceRegion is also a
2383 // possibility here.
2384
2385 if (isa<AllocaRegion>(R))
2386 HandleFreeAlloca(C, ArgVal, ArgExpr->getSourceRange());
2387 else
2388 HandleNonHeapDealloc(C, ArgVal, ArgExpr->getSourceRange(), ParentExpr,
2389 Family);
2390
2391 return nullptr;
2392 }
2393
2394 const SymbolicRegion *SrBase = dyn_cast<SymbolicRegion>(R->getBaseRegion());
2395 // Various cases could lead to non-symbol values here.
2396 // For now, ignore them.
2397 if (!SrBase)
2398 return nullptr;
2399
2400 SymbolRef SymBase = SrBase->getSymbol();
2401 const RefState *RsBase = State->get<RegionState>(SymBase);
2402 SymbolRef PreviousRetStatusSymbol = nullptr;
2403
2404 IsKnownToBeAllocated = RsBase && RsBase->isAllocated();
2405
2406 if (RsBase) {
2407
2408 // Memory returned by alloca() shouldn't be freed.
2409 if (RsBase->getAllocationFamily().Kind == AF_Alloca) {
2410 HandleFreeAlloca(C, ArgVal, ArgExpr->getSourceRange());
2411 return nullptr;
2412 }
2413
2414 // Check for double free first.
2415 if ((RsBase->isReleased() || RsBase->isRelinquished()) &&
2416 !didPreviousFreeFail(State, SymBase, PreviousRetStatusSymbol)) {
2417 HandleDoubleFree(C, ParentExpr->getSourceRange(), RsBase->isReleased(),
2418 SymBase, PreviousRetStatusSymbol);
2419 return nullptr;
2420 }
2421
2422 // If the pointer is allocated or escaped, but we are now trying to free it,
2423 // check that the call to free is proper.
2424 if (RsBase->isAllocated() || RsBase->isEscaped()) {
2425
2426 // Check if an expected deallocation function matches the real one.
2427 bool DeallocMatchesAlloc = RsBase->getAllocationFamily() == Family;
2428 if (!DeallocMatchesAlloc) {
2429 HandleMismatchedDealloc(C, ArgExpr->getSourceRange(), ParentExpr,
2430 RsBase, SymBase, Hold);
2431 return nullptr;
2432 }
2433
2434 // Check if the memory location being freed is the actual location
2435 // allocated, or an offset.
2436 RegionOffset Offset = R->getAsOffset();
2437 if (Offset.isValid() &&
2438 !Offset.hasSymbolicOffset() &&
2439 Offset.getOffset() != 0) {
2440 const Expr *AllocExpr = cast<Expr>(RsBase->getStmt());
2441 HandleOffsetFree(C, ArgVal, ArgExpr->getSourceRange(), ParentExpr,
2442 Family, AllocExpr);
2443 return nullptr;
2444 }
2445 }
2446 }
2447
2448 if (SymBase->getType()->isFunctionPointerType()) {
2449 HandleFunctionPtrFree(C, ArgVal, ArgExpr->getSourceRange(), ParentExpr,
2450 Family);
2451 return nullptr;
2452 }
2453
2454 // Clean out the info on previous call to free return info.
2455 State = State->remove<FreeReturnValue>(SymBase);
2456
2457 // Keep track of the return value. If it is NULL, we will know that free
2458 // failed.
2459 if (ReturnsNullOnFailure) {
2460 SVal RetVal = C.getSVal(ParentExpr);
2461 SymbolRef RetStatusSymbol = RetVal.getAsSymbol();
2462 if (RetStatusSymbol) {
2463 C.getSymbolManager().addSymbolDependency(SymBase, RetStatusSymbol);
2464 State = State->set<FreeReturnValue>(SymBase, RetStatusSymbol);
2465 }
2466 }
2467
2468 // If we don't know anything about this symbol, a free on it may be totally
2469 // valid. If this is the case, lets assume that the allocation family of the
2470 // freeing function is the same as the symbols allocation family, and go with
2471 // that.
2472 assert(!RsBase || (RsBase && RsBase->getAllocationFamily() == Family));
2473
2474 // Assume that after memory is freed, it contains unknown values. This
2475 // conforts languages standards, since reading from freed memory is considered
2476 // UB and may result in arbitrary value.
2477 State = State->invalidateRegions({location}, Call.getCFGElementRef(),
2478 C.blockCount(), C.getStackFrame(),
2479 /*CausesPointerEscape=*/false,
2480 /*InvalidatedSymbols=*/nullptr);
2481
2482 // Normal free.
2483 if (Hold)
2484 return State->set<RegionState>(SymBase,
2485 RefState::getRelinquished(Family,
2486 ParentExpr));
2487
2488 return State->set<RegionState>(SymBase,
2489 RefState::getReleased(Family, ParentExpr));
2490}
2491
2492template <class T>
2493const T *MallocChecker::getRelevantFrontendAs(AllocationFamily Family) const {
2494 switch (Family.Kind) {
2495 case AF_Malloc:
2496 case AF_Alloca:
2497 case AF_Custom:
2498 case AF_IfNameIndex:
2499 return MallocChecker.getAs<T>();
2500 case AF_CXXNew:
2501 case AF_CXXNewArray: {
2502 const T *ND = NewDeleteChecker.getAs<T>();
2503 const T *NDL = NewDeleteLeaksChecker.getAs<T>();
2504 // Bugs corresponding to C++ new/delete allocations are split between these
2505 // two frontends.
2506 if constexpr (std::is_same_v<T, CheckerFrontend>) {
2507 assert(ND && NDL && "Casting to CheckerFrontend always succeeds");
2508 // Prefer NewDelete unless it's disabled and NewDeleteLeaks is enabled.
2509 return (!ND->isEnabled() && NDL->isEnabled()) ? NDL : ND;
2510 }
2511 assert(!(ND && NDL) &&
2512 "NewDelete and NewDeleteLeaks must not share a bug type");
2513 return ND ? ND : NDL;
2514 }
2515 case AF_InnerBuffer:
2516 return InnerPointerChecker.getAs<T>();
2517 case AF_None:
2518 assert(false && "no family");
2519 return nullptr;
2520 }
2521 assert(false && "unhandled family");
2522 return nullptr;
2523}
2524template <class T>
2525const T *MallocChecker::getRelevantFrontendAs(CheckerContext &C,
2526 SymbolRef Sym) const {
2527 if (C.getState()->contains<ReallocSizeZeroSymbols>(Sym))
2528 return MallocChecker.getAs<T>();
2529
2530 const RefState *RS = C.getState()->get<RegionState>(Sym);
2531 assert(RS);
2532 return getRelevantFrontendAs<T>(RS->getAllocationFamily());
2533}
2534
2535bool MallocChecker::SummarizeValue(raw_ostream &os, SVal V) {
2536 if (std::optional<nonloc::ConcreteInt> IntVal =
2537 V.getAs<nonloc::ConcreteInt>())
2538 os << "an integer (" << IntVal->getValue() << ")";
2539 else if (std::optional<loc::ConcreteInt> ConstAddr =
2540 V.getAs<loc::ConcreteInt>())
2541 os << "a constant address (" << ConstAddr->getValue() << ")";
2542 else if (std::optional<loc::GotoLabel> Label = V.getAs<loc::GotoLabel>())
2543 os << "the address of the label '" << Label->getLabel()->getName() << "'";
2544 else
2545 return false;
2546
2547 return true;
2548}
2549
2550bool MallocChecker::SummarizeRegion(ProgramStateRef State, raw_ostream &os,
2551 const MemRegion *MR) {
2552 switch (MR->getKind()) {
2553 case MemRegion::FunctionCodeRegionKind: {
2554 const NamedDecl *FD = cast<FunctionCodeRegion>(MR)->getDecl();
2555 if (FD)
2556 os << "the address of the function '" << *FD << '\'';
2557 else
2558 os << "the address of a function";
2559 return true;
2560 }
2561 case MemRegion::BlockCodeRegionKind:
2562 os << "block text";
2563 return true;
2564 case MemRegion::BlockDataRegionKind:
2565 // FIXME: where the block came from?
2566 os << "a block";
2567 return true;
2568 default: {
2569 const MemSpaceRegion *MS = MR->getMemorySpace(State);
2570
2572 const VarRegion *VR = dyn_cast<VarRegion>(MR);
2573 const VarDecl *VD;
2574 if (VR)
2575 VD = VR->getDecl();
2576 else
2577 VD = nullptr;
2578
2579 if (VD)
2580 os << "the address of the local variable '" << VD->getName() << "'";
2581 else
2582 os << "the address of a local stack variable";
2583 return true;
2584 }
2585
2587 const VarRegion *VR = dyn_cast<VarRegion>(MR);
2588 const VarDecl *VD;
2589 if (VR)
2590 VD = VR->getDecl();
2591 else
2592 VD = nullptr;
2593
2594 if (VD)
2595 os << "the address of the parameter '" << VD->getName() << "'";
2596 else
2597 os << "the address of a parameter";
2598 return true;
2599 }
2600
2601 if (isa<GlobalsSpaceRegion>(MS)) {
2602 const VarRegion *VR = dyn_cast<VarRegion>(MR);
2603 const VarDecl *VD;
2604 if (VR)
2605 VD = VR->getDecl();
2606 else
2607 VD = nullptr;
2608
2609 if (VD) {
2610 if (VD->isStaticLocal())
2611 os << "the address of the static variable '" << VD->getName() << "'";
2612 else
2613 os << "the address of the global variable '" << VD->getName() << "'";
2614 } else
2615 os << "the address of a global variable";
2616 return true;
2617 }
2618
2619 return false;
2620 }
2621 }
2622}
2623
2624void MallocChecker::HandleNonHeapDealloc(CheckerContext &C, SVal ArgVal,
2625 SourceRange Range,
2626 const Expr *DeallocExpr,
2627 AllocationFamily Family) const {
2628 const BadFree *Frontend = getRelevantFrontendAs<BadFree>(Family);
2629 if (!Frontend)
2630 return;
2631 if (!Frontend->isEnabled()) {
2632 C.addSink();
2633 return;
2634 }
2635
2636 if (ExplodedNode *N = C.addSink()) {
2637 SmallString<100> buf;
2638 llvm::raw_svector_ostream os(buf);
2639
2640 const MemRegion *MR = ArgVal.getAsRegion();
2641 while (const ElementRegion *ER = dyn_cast_or_null<ElementRegion>(MR))
2642 MR = ER->getSuperRegion();
2643
2644 os << "Argument to ";
2645 if (!printMemFnName(os, C, DeallocExpr))
2646 os << "deallocator";
2647
2648 os << " is ";
2649 bool Summarized =
2650 MR ? SummarizeRegion(C.getState(), os, MR) : SummarizeValue(os, ArgVal);
2651 if (Summarized)
2652 os << ", which is not memory allocated by ";
2653 else
2654 os << "not memory allocated by ";
2655
2656 printExpectedAllocName(os, Family);
2657
2658 auto R = std::make_unique<PathSensitiveBugReport>(Frontend->BadFreeBug,
2659 os.str(), N);
2660 R->markInteresting(MR);
2661 R->addRange(Range);
2662 C.emitReport(std::move(R));
2663 }
2664}
2665
2666void MallocChecker::HandleFreeAlloca(CheckerContext &C, SVal ArgVal,
2667 SourceRange Range) const {
2668 const FreeAlloca *Frontend;
2669
2670 if (MallocChecker.isEnabled())
2671 Frontend = &MallocChecker;
2672 else if (MismatchedDeallocatorChecker.isEnabled())
2673 Frontend = &MismatchedDeallocatorChecker;
2674 else {
2675 C.addSink();
2676 return;
2677 }
2678
2679 if (ExplodedNode *N = C.addSink()) {
2680 auto R = std::make_unique<PathSensitiveBugReport>(
2681 Frontend->FreeAllocaBug,
2682 "Memory allocated by 'alloca()' should not be deallocated", N);
2683 R->markInteresting(ArgVal.getAsRegion());
2684 R->addRange(Range);
2685 C.emitReport(std::move(R));
2686 }
2687}
2688
2689void MallocChecker::HandleMismatchedDealloc(CheckerContext &C,
2690 SourceRange Range,
2691 const Expr *DeallocExpr,
2692 const RefState *RS, SymbolRef Sym,
2693 bool OwnershipTransferred) const {
2694 if (!MismatchedDeallocatorChecker.isEnabled()) {
2695 C.addSink();
2696 return;
2697 }
2698
2699 if (ExplodedNode *N = C.addSink()) {
2700 SmallString<100> buf;
2701 llvm::raw_svector_ostream os(buf);
2702
2703 const Expr *AllocExpr = cast<Expr>(RS->getStmt());
2704 SmallString<20> AllocBuf;
2705 llvm::raw_svector_ostream AllocOs(AllocBuf);
2706 SmallString<20> DeallocBuf;
2707 llvm::raw_svector_ostream DeallocOs(DeallocBuf);
2708
2709 if (OwnershipTransferred) {
2710 if (printMemFnName(DeallocOs, C, DeallocExpr))
2711 os << DeallocOs.str() << " cannot";
2712 else
2713 os << "Cannot";
2714
2715 os << " take ownership of memory";
2716
2717 if (printMemFnName(AllocOs, C, AllocExpr))
2718 os << " allocated by " << AllocOs.str();
2719 } else {
2720 os << "Memory";
2721 if (printMemFnName(AllocOs, C, AllocExpr))
2722 os << " allocated by " << AllocOs.str();
2723
2724 os << " should be deallocated by ";
2725 printExpectedDeallocName(os, RS->getAllocationFamily());
2726
2727 if (printMemFnName(DeallocOs, C, DeallocExpr))
2728 os << ", not " << DeallocOs.str();
2729
2730 printOwnershipTakesList(os, C, DeallocExpr);
2731 }
2732
2733 auto R = std::make_unique<PathSensitiveBugReport>(
2734 MismatchedDeallocatorChecker.MismatchedDeallocBug, os.str(), N);
2735 R->markInteresting(Sym);
2736 R->addRange(Range);
2737 R->addVisitor<MallocBugVisitor>(Sym);
2738 C.emitReport(std::move(R));
2739 }
2740}
2741
2742void MallocChecker::HandleOffsetFree(CheckerContext &C, SVal ArgVal,
2743 SourceRange Range, const Expr *DeallocExpr,
2744 AllocationFamily Family,
2745 const Expr *AllocExpr) const {
2746 const OffsetFree *Frontend = getRelevantFrontendAs<OffsetFree>(Family);
2747 if (!Frontend)
2748 return;
2749 if (!Frontend->isEnabled()) {
2750 C.addSink();
2751 return;
2752 }
2753
2754 ExplodedNode *N = C.addSink();
2755 if (!N)
2756 return;
2757
2758 SmallString<100> buf;
2759 llvm::raw_svector_ostream os(buf);
2760 SmallString<20> AllocNameBuf;
2761 llvm::raw_svector_ostream AllocNameOs(AllocNameBuf);
2762
2763 const MemRegion *MR = ArgVal.getAsRegion();
2764 assert(MR && "Only MemRegion based symbols can have offset free errors");
2765
2766 RegionOffset Offset = MR->getAsOffset();
2767 assert((Offset.isValid() &&
2768 !Offset.hasSymbolicOffset() &&
2769 Offset.getOffset() != 0) &&
2770 "Only symbols with a valid offset can have offset free errors");
2771
2772 int offsetBytes = Offset.getOffset() / C.getASTContext().getCharWidth();
2773
2774 os << "Argument to ";
2775 if (!printMemFnName(os, C, DeallocExpr))
2776 os << "deallocator";
2777 os << " is offset by "
2778 << offsetBytes
2779 << " "
2780 << ((abs(offsetBytes) > 1) ? "bytes" : "byte")
2781 << " from the start of ";
2782 if (AllocExpr && printMemFnName(AllocNameOs, C, AllocExpr))
2783 os << "memory allocated by " << AllocNameOs.str();
2784 else
2785 os << "allocated memory";
2786
2787 auto R = std::make_unique<PathSensitiveBugReport>(Frontend->OffsetFreeBug,
2788 os.str(), N);
2789 R->markInteresting(MR->getBaseRegion());
2790 R->addRange(Range);
2791 C.emitReport(std::move(R));
2792}
2793
2794void MallocChecker::HandleUseAfterFree(CheckerContext &C, SourceRange Range,
2795 SymbolRef Sym) const {
2796 const UseFree *Frontend = getRelevantFrontendAs<UseFree>(C, Sym);
2797 if (!Frontend)
2798 return;
2799 if (!Frontend->isEnabled()) {
2800 C.addSink();
2801 return;
2802 }
2803
2804 if (ExplodedNode *N = C.addSink()) {
2805 AllocationFamily AF =
2806 C.getState()->get<RegionState>(Sym)->getAllocationFamily();
2807
2808 auto R = std::make_unique<PathSensitiveBugReport>(
2809 Frontend->UseFreeBug,
2810 AF.Kind == AF_InnerBuffer
2811 ? "Inner pointer of container used after re/deallocation"
2812 : "Use of memory after it is released",
2813 N);
2814
2815 R->markInteresting(Sym);
2816 R->addRange(Range);
2817 R->addVisitor<MallocBugVisitor>(Sym);
2818
2819 if (AF.Kind == AF_InnerBuffer)
2821
2822 C.emitReport(std::move(R));
2823 }
2824}
2825
2826void MallocChecker::HandleDoubleFree(CheckerContext &C, SourceRange Range,
2827 bool Released, SymbolRef Sym,
2828 SymbolRef PrevSym) const {
2829 const DoubleFree *Frontend = getRelevantFrontendAs<DoubleFree>(C, Sym);
2830 if (!Frontend)
2831 return;
2832 if (!Frontend->isEnabled()) {
2833 C.addSink();
2834 return;
2835 }
2836
2837 if (ExplodedNode *N = C.addSink()) {
2838 auto R = std::make_unique<PathSensitiveBugReport>(
2839 Frontend->DoubleFreeBug,
2840 (Released ? "Attempt to release already released memory"
2841 : "Attempt to release non-owned memory"),
2842 N);
2843 if (Range.isValid())
2844 R->addRange(Range);
2845 R->markInteresting(Sym);
2846 if (PrevSym)
2847 R->markInteresting(PrevSym);
2848 R->addVisitor<MallocBugVisitor>(Sym);
2849 C.emitReport(std::move(R));
2850 }
2851}
2852
2853void MallocChecker::HandleUseZeroAlloc(CheckerContext &C, SourceRange Range,
2854 SymbolRef Sym) const {
2855 const UseZeroAllocated *Frontend =
2856 getRelevantFrontendAs<UseZeroAllocated>(C, Sym);
2857 if (!Frontend)
2858 return;
2859 if (!Frontend->isEnabled()) {
2860 C.addSink();
2861 return;
2862 }
2863
2864 if (ExplodedNode *N = C.addSink()) {
2865 auto R = std::make_unique<PathSensitiveBugReport>(
2866 Frontend->UseZeroAllocatedBug, "Use of memory allocated with size zero",
2867 N);
2868
2869 R->addRange(Range);
2870 if (Sym) {
2871 R->markInteresting(Sym);
2872 R->addVisitor<MallocBugVisitor>(Sym);
2873 }
2874 C.emitReport(std::move(R));
2875 }
2876}
2877
2878void MallocChecker::HandleFunctionPtrFree(CheckerContext &C, SVal ArgVal,
2879 SourceRange Range,
2880 const Expr *FreeExpr,
2881 AllocationFamily Family) const {
2882 const BadFree *Frontend = getRelevantFrontendAs<BadFree>(Family);
2883 if (!Frontend)
2884 return;
2885 if (!Frontend->isEnabled()) {
2886 C.addSink();
2887 return;
2888 }
2889
2890 if (ExplodedNode *N = C.addSink()) {
2891 SmallString<100> Buf;
2892 llvm::raw_svector_ostream Os(Buf);
2893
2894 const MemRegion *MR = ArgVal.getAsRegion();
2895 while (const ElementRegion *ER = dyn_cast_or_null<ElementRegion>(MR))
2896 MR = ER->getSuperRegion();
2897
2898 Os << "Argument to ";
2899 if (!printMemFnName(Os, C, FreeExpr))
2900 Os << "deallocator";
2901
2902 Os << " is a function pointer";
2903
2904 auto R = std::make_unique<PathSensitiveBugReport>(Frontend->BadFreeBug,
2905 Os.str(), N);
2906 R->markInteresting(MR);
2907 R->addRange(Range);
2908 C.emitReport(std::move(R));
2909 }
2910}
2911
2913MallocChecker::ReallocMemAux(CheckerContext &C, const CallEvent &Call,
2914 bool ShouldFreeOnFail, ProgramStateRef State,
2915 AllocationFamily Family, bool SuffixWithN) const {
2916 if (!State)
2917 return nullptr;
2918
2919 const CallExpr *CE = cast<CallExpr>(Call.getOriginExpr());
2920
2921 if ((SuffixWithN && CE->getNumArgs() < 3) || CE->getNumArgs() < 2)
2922 return nullptr;
2923
2924 const Expr *arg0Expr = CE->getArg(0);
2925 SVal Arg0Val = C.getSVal(arg0Expr);
2926 if (!isa<DefinedOrUnknownSVal>(Arg0Val))
2927 return nullptr;
2928 DefinedOrUnknownSVal arg0Val = Arg0Val.castAs<DefinedOrUnknownSVal>();
2929
2930 SValBuilder &svalBuilder = C.getSValBuilder();
2931
2932 DefinedOrUnknownSVal PtrEQ = svalBuilder.evalEQ(
2933 State, arg0Val, svalBuilder.makeNullWithType(arg0Expr->getType()));
2934
2935 // Get the size argument.
2936 const Expr *Arg1 = CE->getArg(1);
2937
2938 // Get the value of the size argument.
2939 SVal TotalSize = C.getSVal(Arg1);
2940 if (SuffixWithN)
2941 TotalSize = evalMulForBufferSize(C, Arg1, CE->getArg(2));
2942 if (!isa<DefinedOrUnknownSVal>(TotalSize))
2943 return nullptr;
2944
2945 // Compare the size argument to 0.
2946 DefinedOrUnknownSVal SizeZero = svalBuilder.evalEQ(
2947 State, TotalSize.castAs<DefinedOrUnknownSVal>(),
2948 svalBuilder.makeIntValWithWidth(
2949 svalBuilder.getContext().getCanonicalSizeType(), 0));
2950
2951 ProgramStateRef StatePtrIsNull, StatePtrNotNull;
2952 std::tie(StatePtrIsNull, StatePtrNotNull) = State->assume(PtrEQ);
2953 ProgramStateRef StateSizeIsZero, StateSizeNotZero;
2954 std::tie(StateSizeIsZero, StateSizeNotZero) = State->assume(SizeZero);
2955 // We only assume exceptional states if they are definitely true; if the
2956 // state is under-constrained, assume regular realloc behavior.
2957 bool PrtIsNull = StatePtrIsNull && !StatePtrNotNull;
2958 bool SizeIsZero = StateSizeIsZero && !StateSizeNotZero;
2959
2960 // If the ptr is NULL and the size is not 0, the call is equivalent to
2961 // malloc(size).
2962 if (PrtIsNull && !SizeIsZero) {
2963 ProgramStateRef stateMalloc = MallocMemAux(
2964 C, Call, TotalSize, UndefinedVal(), StatePtrIsNull, Family);
2965 return stateMalloc;
2966 }
2967
2968 // Proccess as allocation of 0 bytes.
2969 if (PrtIsNull && SizeIsZero)
2970 return State;
2971
2972 assert(!PrtIsNull);
2973
2974 bool IsKnownToBeAllocated = false;
2975
2976 // If the size is 0, free the memory.
2977 if (SizeIsZero)
2978 // The semantics of the return value are:
2979 // If size was equal to 0, either NULL or a pointer suitable to be passed
2980 // to free() is returned. We just free the input pointer and do not add
2981 // any constrains on the output pointer.
2982 if (ProgramStateRef stateFree = FreeMemAux(
2983 C, Call, StateSizeIsZero, 0, false, IsKnownToBeAllocated, Family))
2984 return stateFree;
2985
2986 // Default behavior.
2987 if (ProgramStateRef stateFree =
2988 FreeMemAux(C, Call, State, 0, false, IsKnownToBeAllocated, Family)) {
2989
2990 ProgramStateRef stateRealloc =
2991 MallocMemAux(C, Call, TotalSize, UnknownVal(), stateFree, Family);
2992 if (!stateRealloc)
2993 return nullptr;
2994
2995 OwnershipAfterReallocKind Kind = OAR_ToBeFreedAfterFailure;
2996 if (ShouldFreeOnFail)
2997 Kind = OAR_FreeOnFailure;
2998 else if (!IsKnownToBeAllocated)
2999 Kind = OAR_DoNotTrackAfterFailure;
3000
3001 // Get the from and to pointer symbols as in toPtr = realloc(fromPtr, size).
3002 SymbolRef FromPtr = arg0Val.getLocSymbolInBase();
3003 SVal RetVal = stateRealloc->getSVal(CE, C.getStackFrame());
3004 SymbolRef ToPtr = RetVal.getAsSymbol();
3005 assert(FromPtr && ToPtr &&
3006 "By this point, FreeMemAux and MallocMemAux should have checked "
3007 "whether the argument or the return value is symbolic!");
3008
3009 // Record the info about the reallocated symbol so that we could properly
3010 // process failed reallocation.
3011 stateRealloc = stateRealloc->set<ReallocPairs>(ToPtr,
3012 ReallocPair(FromPtr, Kind));
3013 // The reallocated symbol should stay alive for as long as the new symbol.
3014 C.getSymbolManager().addSymbolDependency(ToPtr, FromPtr);
3015 return stateRealloc;
3016 }
3017 return nullptr;
3018}
3019
3020ProgramStateRef MallocChecker::CallocMem(CheckerContext &C,
3021 const CallEvent &Call,
3022 ProgramStateRef State) const {
3023 if (!State)
3024 return nullptr;
3025
3026 if (Call.getNumArgs() < 2)
3027 return nullptr;
3028
3029 SValBuilder &svalBuilder = C.getSValBuilder();
3030 SVal zeroVal = svalBuilder.makeZeroVal(svalBuilder.getContext().CharTy);
3031 SVal TotalSize =
3032 evalMulForBufferSize(C, Call.getArgExpr(0), Call.getArgExpr(1));
3033
3034 return MallocMemAux(C, Call, TotalSize, zeroVal, State,
3035 AllocationFamily(AF_Malloc));
3036}
3037
3038MallocChecker::LeakInfo MallocChecker::getAllocationSite(const ExplodedNode *N,
3039 SymbolRef Sym,
3040 CheckerContext &C) {
3041 const StackFrame *LeakStackFrame = N->getStackFrame();
3042 // Walk the ExplodedGraph backwards and find the first node that referred to
3043 // the tracked symbol.
3044 const ExplodedNode *AllocNode = N;
3045 const MemRegion *ReferenceRegion = nullptr;
3046
3047 while (N) {
3048 ProgramStateRef State = N->getState();
3049 if (!State->get<RegionState>(Sym))
3050 break;
3051
3052 // Find the most recent expression bound to the symbol in the current
3053 // context.
3054 if (!ReferenceRegion) {
3055 if (const MemRegion *MR = C.getLocationRegionIfPostStore(N)) {
3056 SVal Val = State->getSVal(MR);
3057 if (Val.getAsLocSymbol() == Sym) {
3058 const VarRegion *VR = MR->getBaseRegion()->getAs<VarRegion>();
3059 // Do not show local variables belonging to a function other than
3060 // where the error is reported.
3061 if (!VR || (VR->getStackFrame() == LeakStackFrame))
3062 ReferenceRegion = MR;
3063 }
3064 }
3065 }
3066
3067 // Allocation node, is the last node in the current or parent context in
3068 // which the symbol was tracked.
3069 const StackFrame *NSF = N->getStackFrame();
3070 if (NSF == LeakStackFrame || NSF->isParentOf(LeakStackFrame))
3071 AllocNode = N;
3072 N = N->pred_empty() ? nullptr : *(N->pred_begin());
3073 }
3074
3075 return LeakInfo(AllocNode, ReferenceRegion);
3076}
3077
3078void MallocChecker::HandleLeak(SymbolRef Sym, ExplodedNode *N,
3079 CheckerContext &C) const {
3080 assert(N && "HandleLeak is only called with a non-null node");
3081
3082 const RefState *RS = C.getState()->get<RegionState>(Sym);
3083 assert(RS && "cannot leak an untracked symbol");
3084 AllocationFamily Family = RS->getAllocationFamily();
3085
3086 if (Family.Kind == AF_Alloca)
3087 return;
3088
3089 const Leak *Frontend = getRelevantFrontendAs<Leak>(Family);
3090 // Note that for leaks we don't add a sink when the relevant frontend is
3091 // disabled because the leak is reported with a non-fatal error node, while
3092 // the sink would be the "silent" alternative of a (fatal) error node.
3093 if (!Frontend || !Frontend->isEnabled())
3094 return;
3095
3096 // Most bug reports are cached at the location where they occurred.
3097 // With leaks, we want to unique them by the location where they were
3098 // allocated, and only report a single path.
3099 PathDiagnosticLocation LocUsedForUniqueing;
3100 const ExplodedNode *AllocNode = nullptr;
3101 const MemRegion *Region = nullptr;
3102 std::tie(AllocNode, Region) = getAllocationSite(N, Sym, C);
3103
3104 const Stmt *AllocationStmt = AllocNode->getStmtForDiagnostics();
3105 if (AllocationStmt)
3106 LocUsedForUniqueing = PathDiagnosticLocation::createBegin(
3107 AllocationStmt, C.getSourceManager(), AllocNode->getStackFrame());
3108
3109 SmallString<200> buf;
3110 llvm::raw_svector_ostream os(buf);
3111 if (Region && Region->canPrintPretty()) {
3112 os << "Potential leak of memory pointed to by ";
3113 Region->printPretty(os);
3114 } else {
3115 os << "Potential memory leak";
3116 }
3117
3118 auto R = std::make_unique<PathSensitiveBugReport>(
3119 Frontend->LeakBug, os.str(), N, LocUsedForUniqueing,
3120 AllocNode->getStackFrame()->getDecl());
3121 R->markInteresting(Sym);
3122 R->addVisitor<MallocBugVisitor>(Sym, true);
3123 if (ShouldRegisterNoOwnershipChangeVisitor)
3124 R->addVisitor<NoMemOwnershipChangeVisitor>(Sym, this);
3125 C.emitReport(std::move(R));
3126}
3127
3128void MallocChecker::checkDeadSymbols(SymbolReaper &SymReaper,
3129 CheckerContext &C) const
3130{
3131 ProgramStateRef state = C.getState();
3132 RegionStateTy OldRS = state->get<RegionState>();
3133 RegionStateTy::Factory &F = state->get_context<RegionState>();
3134
3135 RegionStateTy RS = OldRS;
3136 SmallVector<SymbolRef, 2> Errors;
3137 for (auto [Sym, State] : RS) {
3138 if (SymReaper.isDead(Sym)) {
3139 if (State.isAllocated())
3140 Errors.push_back(Sym);
3141 // Remove the dead symbol from the map.
3142 RS = F.remove(RS, Sym);
3143 }
3144 }
3145
3146 if (RS == OldRS) {
3147 // We shouldn't have touched other maps yet.
3148 assert(state->get<ReallocPairs>() ==
3149 C.getState()->get<ReallocPairs>());
3150 assert(state->get<FreeReturnValue>() ==
3151 C.getState()->get<FreeReturnValue>());
3152 return;
3153 }
3154
3155 // Cleanup the Realloc Pairs Map.
3156 ReallocPairsTy RP = state->get<ReallocPairs>();
3157 for (auto [Sym, ReallocPair] : RP) {
3158 if (SymReaper.isDead(Sym) || SymReaper.isDead(ReallocPair.ReallocatedSym)) {
3159 state = state->remove<ReallocPairs>(Sym);
3160 }
3161 }
3162
3163 // Cleanup the FreeReturnValue Map.
3164 FreeReturnValueTy FR = state->get<FreeReturnValue>();
3165 for (auto [Sym, RetSym] : FR) {
3166 if (SymReaper.isDead(Sym) || SymReaper.isDead(RetSym)) {
3167 state = state->remove<FreeReturnValue>(Sym);
3168 }
3169 }
3170
3171 // Generate leak node.
3172 ExplodedNode *N = C.getPredecessor();
3173 if (!Errors.empty()) {
3174 N = C.generateNonFatalErrorNode(C.getState());
3175 if (N) {
3176 for (SymbolRef Sym : Errors) {
3177 HandleLeak(Sym, N, C);
3178 }
3179 }
3180 }
3181
3182 C.addTransition(state->set<RegionState>(RS), N);
3183}
3184
3185// Allowlist of owning smart pointers we want to recognize.
3186// Start with unique_ptr and shared_ptr; weak_ptr is excluded intentionally
3187// because it does not own the pointee.
3188static bool isSmartPtrName(StringRef Name) {
3189 return Name == "unique_ptr" || Name == "shared_ptr";
3190}
3191
3192// Check if a type is a smart owning pointer type.
3193static bool isSmartPtrType(QualType QT) {
3194 QT = QT->getCanonicalTypeUnqualified();
3195
3196 if (const auto *TST = QT->getAs<TemplateSpecializationType>()) {
3197 const TemplateDecl *TD = TST->getTemplateName().getAsTemplateDecl();
3198 if (!TD)
3199 return false;
3200
3201 const auto *ND = dyn_cast_or_null<NamedDecl>(TD->getTemplatedDecl());
3202 if (!ND)
3203 return false;
3204
3205 // For broader coverage we recognize all template classes with names that
3206 // match the allowlist even if they are not declared in namespace 'std'.
3207 return isSmartPtrName(ND->getName());
3208 }
3209
3210 return false;
3211}
3212
3213/// Helper struct for collecting smart owning pointer field regions.
3214/// This allows both hasSmartPtrField and
3215/// collectSmartPtrFieldRegions to share the same traversal logic,
3216/// ensuring consistency.
3220 llvm::SmallPtrSetImpl<const MemRegion *> *Out;
3221
3223 llvm::SmallPtrSetImpl<const MemRegion *> &Out)
3224 : Reg(Reg), C(&C), Out(&Out) {}
3225
3226 void consume(const FieldDecl *FD) {
3227 SVal L = C->getState()->getLValue(FD, loc::MemRegionVal(Reg));
3228 if (const MemRegion *FR = L.getAsRegion())
3229 Out->insert(FR);
3230 }
3231
3232 std::optional<FieldConsumer> switchToBase(const CXXRecordDecl *BaseDecl,
3233 bool IsVirtual) {
3234 // Get the base class region
3235 SVal BaseL =
3236 C->getState()->getLValue(BaseDecl, Reg->getAs<SubRegion>(), IsVirtual);
3237 if (const MemRegion *BaseObjRegion = BaseL.getAsRegion()) {
3238 // Return a consumer for the base class
3239 return FieldConsumer{BaseObjRegion, *C, *Out};
3240 }
3241 return std::nullopt;
3242 }
3243};
3244
3245/// Check if a record type has smart owning pointer fields (directly or in base
3246/// classes). When FC is provided, also collect the field regions.
3247///
3248/// This function has dual behavior:
3249/// - When FC is nullopt: Returns true if smart pointer fields are found
3250/// - When FC is provided: Always returns false, but collects field regions
3251/// as a side effect through the FieldConsumer
3252///
3253/// Note: When FC is provided, the return value should be ignored since the
3254/// function performs full traversal for collection and always returns false
3255/// to avoid early termination.
3256static bool hasSmartPtrField(const CXXRecordDecl *CRD,
3257 std::optional<FieldConsumer> FC = std::nullopt) {
3258 // Check direct fields
3259 for (const FieldDecl *FD : CRD->fields()) {
3260 if (isSmartPtrType(FD->getType())) {
3261 if (!FC)
3262 return true;
3263 FC->consume(FD);
3264 }
3265 }
3266
3267 // Check fields from base classes
3268 for (const CXXBaseSpecifier &BaseSpec : CRD->bases()) {
3269 if (const CXXRecordDecl *BaseDecl =
3270 BaseSpec.getType()->getAsCXXRecordDecl()) {
3271 std::optional<FieldConsumer> NewFC;
3272 if (FC) {
3273 NewFC = FC->switchToBase(BaseDecl, BaseSpec.isVirtual());
3274 if (!NewFC)
3275 continue;
3276 }
3277 bool Found = hasSmartPtrField(BaseDecl, NewFC);
3278 if (Found && !FC)
3279 return true;
3280 }
3281 }
3282 return false;
3283}
3284
3285/// Check if an expression is an rvalue record type passed by value.
3286static bool isRvalueByValueRecord(const Expr *AE) {
3287 if (AE->isGLValue())
3288 return false;
3289
3290 QualType T = AE->getType();
3291 if (!T->isRecordType() || T->isReferenceType())
3292 return false;
3293
3294 // Accept common temp/construct forms but don't overfit.
3297}
3298
3299/// Check if an expression is an rvalue record with smart owning pointer fields
3300/// passed by value.
3302 if (!isRvalueByValueRecord(AE))
3303 return false;
3304
3305 const auto *CRD = AE->getType()->getAsCXXRecordDecl();
3306 return CRD && hasSmartPtrField(CRD);
3307}
3308
3309/// Check if a CXXRecordDecl has a name matching recognized smart pointer names.
3310static bool isSmartPtrRecord(const CXXRecordDecl *RD) {
3311 if (!RD)
3312 return false;
3313
3314 // Check the record name directly and accept both std and custom smart pointer
3315 // implementations for broader coverage
3316 return isSmartPtrName(RD->getName());
3317}
3318
3319/// Check if a call is a constructor of a smart owning pointer class that
3320/// accepts pointer parameters.
3321static bool isSmartPtrCall(const CallEvent &Call) {
3322 // Only check for smart pointer constructor calls
3323 const auto *CD = dyn_cast_or_null<CXXConstructorDecl>(Call.getDecl());
3324 if (!CD)
3325 return false;
3326
3327 const auto *RD = CD->getParent();
3328 if (!isSmartPtrRecord(RD))
3329 return false;
3330
3331 // Check if constructor takes a pointer parameter
3332 for (const auto *Param : CD->parameters()) {
3333 QualType ParamType = Param->getType();
3334 if (ParamType->isPointerType() && !ParamType->isFunctionPointerType() &&
3335 !ParamType->isVoidPointerType()) {
3336 return true;
3337 }
3338 }
3339
3340 return false;
3341}
3342
3343/// Collect memory regions of smart owning pointer fields from a record type
3344/// (including fields from base classes).
3345static void
3348 llvm::SmallPtrSetImpl<const MemRegion *> &Out) {
3349 if (!Reg)
3350 return;
3351
3352 const auto *CRD = RecQT->getAsCXXRecordDecl();
3353 if (!CRD)
3354 return;
3355
3356 FieldConsumer FC{Reg, C, Out};
3357 hasSmartPtrField(CRD, FC);
3358}
3359
3360/// Handle smart pointer constructor calls by escaping allocated symbols
3361/// that are passed as pointer arguments to the constructor.
3362ProgramStateRef MallocChecker::handleSmartPointerConstructorArguments(
3363 const CallEvent &Call, ProgramStateRef State) const {
3364 const auto *CD = cast<CXXConstructorDecl>(Call.getDecl());
3365 for (unsigned I = 0, E = std::min(Call.getNumArgs(), CD->getNumParams());
3366 I != E; ++I) {
3367 const Expr *ArgExpr = Call.getArgExpr(I);
3368 if (!ArgExpr)
3369 continue;
3370
3371 QualType ParamType = CD->getParamDecl(I)->getType();
3372 if (ParamType->isPointerType() && !ParamType->isFunctionPointerType() &&
3373 !ParamType->isVoidPointerType()) {
3374 // This argument is a pointer being passed to smart pointer constructor
3375 SVal ArgVal = Call.getArgSVal(I);
3376 SymbolRef Sym = ArgVal.getAsSymbol();
3377 if (Sym && State->contains<RegionState>(Sym)) {
3378 const RefState *RS = State->get<RegionState>(Sym);
3379 if (RS && RS->isAllocated()) {
3380 State = State->set<RegionState>(Sym, RefState::getEscaped(RS));
3381 }
3382 }
3383 }
3384 }
3385 return State;
3386}
3387
3388/// Handle all smart pointer related processing in function calls.
3389/// This includes both direct smart pointer constructor calls and by-value
3390/// arguments containing smart pointer fields.
3391ProgramStateRef MallocChecker::handleSmartPointerRelatedCalls(
3392 const CallEvent &Call, CheckerContext &C, ProgramStateRef State) const {
3393
3394 // Handle direct smart pointer constructor calls first
3395 if (isSmartPtrCall(Call)) {
3396 return handleSmartPointerConstructorArguments(Call, State);
3397 }
3398
3399 // Handle smart pointer fields in by-value record arguments
3400 llvm::SmallPtrSet<const MemRegion *, 8> SmartPtrFieldRoots;
3401 for (unsigned I = 0, E = Call.getNumArgs(); I != E; ++I) {
3402 const Expr *AE = Call.getArgExpr(I);
3403 if (!AE)
3404 continue;
3405 AE = AE->IgnoreParenImpCasts();
3406
3408 continue;
3409
3410 // Find a region for the argument.
3411 SVal ArgVal = Call.getArgSVal(I);
3412 const MemRegion *ArgRegion = ArgVal.getAsRegion();
3413 // Collect direct smart owning pointer field regions
3414 collectSmartPtrFieldRegions(ArgRegion, AE->getType(), C,
3415 SmartPtrFieldRoots);
3416 }
3417
3418 // Escape symbols reachable from smart pointer fields
3419 if (!SmartPtrFieldRoots.empty()) {
3420 SmallVector<const MemRegion *, 8> SmartPtrFieldRootsVec(
3421 SmartPtrFieldRoots.begin(), SmartPtrFieldRoots.end());
3422 State = EscapeTrackedCallback::EscapeTrackedRegionsReachableFrom(
3423 SmartPtrFieldRootsVec, State);
3424 }
3425
3426 return State;
3427}
3428
3429void MallocChecker::checkPostCall(const CallEvent &Call,
3430 CheckerContext &C) const {
3431 // Handle existing post-call handlers first
3432 if (const auto *PostFN = PostFnMap.lookup(Call)) {
3433 (*PostFN)(this, C.getState(), Call, C);
3434 return; // Post-handler already called addTransition, we're done
3435 }
3436
3437 // Handle smart pointer related processing only if no post-handler was called
3438 C.addTransition(handleSmartPointerRelatedCalls(Call, C, C.getState()));
3439}
3440
3441void MallocChecker::checkPreCall(const CallEvent &Call,
3442 CheckerContext &C) const {
3443
3444 if (const auto *DC = dyn_cast<CXXDeallocatorCall>(&Call)) {
3445 const CXXDeleteExpr *DE = DC->getOriginExpr();
3446
3447 // FIXME: I don't see a good reason for restricting the check against
3448 // use-after-free violations to the case when NewDeleteChecker is disabled.
3449 // (However, if NewDeleteChecker is enabled, perhaps it would be better to
3450 // do this check a bit later?)
3451 if (!NewDeleteChecker.isEnabled())
3452 if (SymbolRef Sym = C.getSVal(DE->getArgument()).getAsSymbol())
3453 checkUseAfterFree(Sym, C, DE->getArgument());
3454
3455 if (!isStandardNewDelete(DC->getDecl()))
3456 return;
3457
3458 ProgramStateRef State = C.getState();
3459 bool IsKnownToBeAllocated;
3460 State = FreeMemAux(
3461 C, DE->getArgument(), Call, State,
3462 /*Hold*/ false, IsKnownToBeAllocated,
3463 AllocationFamily(DE->isArrayForm() ? AF_CXXNewArray : AF_CXXNew));
3464
3465 C.addTransition(State);
3466 return;
3467 }
3468
3469 // If we see a `CXXDestructorCall` (that is, an _implicit_ destructor call)
3470 // to a region that's symbolic and known to be already freed, then it must be
3471 // implicitly triggered by a `delete` expression. In this situation we should
3472 // emit a `DoubleFree` report _now_ (before entering the call to the
3473 // destructor) because otherwise the destructor call can trigger a
3474 // use-after-free bug (by accessing any member variable) and that would be
3475 // (technically valid, but) less user-friendly report than the `DoubleFree`.
3476 if (const auto *DC = dyn_cast<CXXDestructorCall>(&Call)) {
3477 SymbolRef Sym = DC->getCXXThisVal().getAsSymbol();
3478 if (!Sym)
3479 return;
3480 if (isReleased(Sym, C)) {
3481 HandleDoubleFree(C, SourceRange(), /*Released=*/true, Sym,
3482 /*PrevSym=*/nullptr);
3483 return;
3484 }
3485 }
3486
3487 // We need to handle getline pre-conditions here before the pointed region
3488 // gets invalidated by StreamChecker
3489 if (const auto *PreFN = PreFnMap.lookup(Call)) {
3490 (*PreFN)(this, C.getState(), Call, C);
3491 return;
3492 }
3493
3494 // We will check for double free in the `evalCall` callback.
3495 // FIXME: It would be more logical to emit double free and use-after-free
3496 // reports via the same pathway (because double free is essentially a specia
3497 // case of use-after-free).
3498 if (const AnyFunctionCall *FC = dyn_cast<AnyFunctionCall>(&Call)) {
3499 const FunctionDecl *FD = FC->getDecl();
3500 if (!FD)
3501 return;
3502
3503 // FIXME: I suspect we should remove `MallocChecker.isEnabled() &&` because
3504 // it's fishy that the enabled/disabled state of one frontend may influence
3505 // reports produced by other frontends.
3506 if (MallocChecker.isEnabled() && isFreeingCall(Call))
3507 return;
3508 }
3509
3510 // Check if the callee of a method is deleted.
3511 if (const CXXInstanceCall *CC = dyn_cast<CXXInstanceCall>(&Call)) {
3512 SymbolRef Sym = CC->getCXXThisVal().getAsSymbol();
3513 if (!Sym || checkUseAfterFree(Sym, C, CC->getCXXThisExpr()))
3514 return;
3515 }
3516
3517 // Check arguments for being used after free.
3518 for (unsigned I = 0, E = Call.getNumArgs(); I != E; ++I) {
3519 SVal ArgSVal = Call.getArgSVal(I);
3520 if (isa<Loc>(ArgSVal)) {
3521 SymbolRef Sym = ArgSVal.getAsSymbol(/*IncludeBaseRegions=*/true);
3522 if (!Sym)
3523 continue;
3524 if (checkUseAfterFree(Sym, C, Call.getArgExpr(I)))
3525 return;
3526 }
3527 }
3528}
3529
3530void MallocChecker::checkPreStmt(const ReturnStmt *S,
3531 CheckerContext &C) const {
3532 checkEscapeOnReturn(S, C);
3533}
3534
3535// In the CFG, automatic destructors come after the return statement.
3536// This callback checks for returning memory that is freed by automatic
3537// destructors, as those cannot be reached in checkPreStmt().
3538void MallocChecker::checkEndFunction(const ReturnStmt *S,
3539 CheckerContext &C) const {
3540 checkEscapeOnReturn(S, C);
3541}
3542
3543void MallocChecker::checkEscapeOnReturn(const ReturnStmt *S,
3544 CheckerContext &C) const {
3545 if (!S)
3546 return;
3547
3548 const Expr *E = S->getRetValue();
3549 if (!E)
3550 return;
3551
3552 // Check if we are returning a symbol.
3553 SVal RetVal = C.getSVal(E);
3554 SymbolRef Sym = RetVal.getAsSymbol();
3555 if (!Sym)
3556 // If we are returning a field of the allocated struct or an array element,
3557 // the callee could still free the memory.
3558 if (const MemRegion *MR = RetVal.getAsRegion())
3560 if (const SymbolicRegion *BMR =
3561 dyn_cast<SymbolicRegion>(MR->getBaseRegion()))
3562 Sym = BMR->getSymbol();
3563
3564 // Check if we are returning freed memory.
3565 if (Sym)
3566 checkUseAfterFree(Sym, C, E);
3567}
3568
3569// TODO: Blocks should be either inlined or should call invalidate regions
3570// upon invocation. After that's in place, special casing here will not be
3571// needed.
3572void MallocChecker::checkPostStmt(const BlockExpr *BE,
3573 CheckerContext &C) const {
3574
3575 // Scan the BlockDecRefExprs for any object the retain count checker
3576 // may be tracking.
3577 if (!BE->getBlockDecl()->hasCaptures())
3578 return;
3579
3580 ProgramStateRef state = C.getState();
3581 const BlockDataRegion *R =
3582 cast<BlockDataRegion>(C.getSVal(BE).getAsRegion());
3583
3584 auto ReferencedVars = R->referenced_vars();
3585 if (ReferencedVars.empty())
3586 return;
3587
3588 SmallVector<const MemRegion *, 10> Regions;
3589 MemRegionManager &MemMgr = C.getSValBuilder().getRegionManager();
3590
3591 for (const auto &Var : ReferencedVars) {
3592 const VarRegion *VR = Var.getCapturedRegion();
3593 if (VR->getSuperRegion() == R) {
3594 VR = MemMgr.getVarRegion(VR->getDecl(), C.getStackFrame());
3595 }
3596 Regions.push_back(VR);
3597 }
3598
3599 state =
3600 state->scanReachableSymbols<StopTrackingCallback>(Regions).getState();
3601 C.addTransition(state);
3602}
3603
3605 assert(Sym);
3606 const RefState *RS = C.getState()->get<RegionState>(Sym);
3607 return (RS && RS->isReleased());
3608}
3609
3610bool MallocChecker::suppressDeallocationsInSuspiciousContexts(
3611 const CallEvent &Call, CheckerContext &C) const {
3612 if (Call.getNumArgs() == 0)
3613 return false;
3614
3615 StringRef FunctionStr = "";
3616 if (const auto *FD = dyn_cast<FunctionDecl>(C.getStackFrame()->getDecl()))
3617 if (const Stmt *Body = FD->getBody())
3618 if (Body->getBeginLoc().isValid())
3619 FunctionStr =
3621 {FD->getBeginLoc(), Body->getBeginLoc()}),
3622 C.getSourceManager(), C.getLangOpts());
3623
3624 // We do not model the Integer Set Library's retain-count based allocation.
3625 if (!FunctionStr.contains("__isl_"))
3626 return false;
3627
3628 ProgramStateRef State = C.getState();
3629
3630 for (const Expr *Arg : cast<CallExpr>(Call.getOriginExpr())->arguments())
3631 if (SymbolRef Sym = C.getSVal(Arg).getAsSymbol())
3632 if (const RefState *RS = State->get<RegionState>(Sym))
3633 State = State->set<RegionState>(Sym, RefState::getEscaped(RS));
3634
3635 C.addTransition(State);
3636 return true;
3637}
3638
3639bool MallocChecker::checkUseAfterFree(SymbolRef Sym, CheckerContext &C,
3640 const Stmt *S) const {
3641
3642 if (isReleased(Sym, C)) {
3643 HandleUseAfterFree(C, S->getSourceRange(), Sym);
3644 return true;
3645 }
3646
3647 return false;
3648}
3649
3650void MallocChecker::checkUseZeroAllocated(SymbolRef Sym, CheckerContext &C,
3651 const Stmt *S) const {
3652 assert(Sym);
3653
3654 if (const RefState *RS = C.getState()->get<RegionState>(Sym)) {
3655 if (RS->isAllocatedOfSizeZero())
3656 HandleUseZeroAlloc(C, RS->getStmt()->getSourceRange(), Sym);
3657 }
3658 else if (C.getState()->contains<ReallocSizeZeroSymbols>(Sym)) {
3659 HandleUseZeroAlloc(C, S->getSourceRange(), Sym);
3660 }
3661}
3662
3663// Check if the location is a freed symbolic region.
3664void MallocChecker::checkLocation(SVal l, bool isLoad, const Stmt *S,
3665 CheckerContext &C) const {
3666 SymbolRef Sym = l.getLocSymbolInBase();
3667 if (Sym) {
3668 checkUseAfterFree(Sym, C, S);
3669 checkUseZeroAllocated(Sym, C, S);
3670 }
3671}
3672
3673// If a symbolic region is assumed to NULL (or another constant), stop tracking
3674// it - assuming that allocation failed on this path.
3675ProgramStateRef MallocChecker::evalAssume(ProgramStateRef state,
3676 SVal Cond,
3677 bool Assumption) const {
3678 RegionStateTy RS = state->get<RegionState>();
3679 for (SymbolRef Sym : llvm::make_first_range(RS)) {
3680 // If the symbol is assumed to be NULL, remove it from consideration.
3681 ConstraintManager &CMgr = state->getConstraintManager();
3682 ConditionTruthVal AllocFailed = CMgr.isNull(state, Sym);
3683 if (AllocFailed.isConstrainedTrue())
3684 state = state->remove<RegionState>(Sym);
3685 }
3686
3687 // Realloc returns 0 when reallocation fails, which means that we should
3688 // restore the state of the pointer being reallocated.
3689 ReallocPairsTy RP = state->get<ReallocPairs>();
3690 for (auto [Sym, ReallocPair] : RP) {
3691 // If the symbol is assumed to be NULL, remove it from consideration.
3692 ConstraintManager &CMgr = state->getConstraintManager();
3693 ConditionTruthVal AllocFailed = CMgr.isNull(state, Sym);
3694 if (!AllocFailed.isConstrainedTrue())
3695 continue;
3696
3697 SymbolRef ReallocSym = ReallocPair.ReallocatedSym;
3698 if (const RefState *RS = state->get<RegionState>(ReallocSym)) {
3699 if (RS->isReleased()) {
3700 switch (ReallocPair.Kind) {
3701 case OAR_ToBeFreedAfterFailure:
3702 state = state->set<RegionState>(ReallocSym,
3703 RefState::getAllocated(RS->getAllocationFamily(), RS->getStmt()));
3704 break;
3705 case OAR_DoNotTrackAfterFailure:
3706 state = state->remove<RegionState>(ReallocSym);
3707 break;
3708 default:
3709 assert(ReallocPair.Kind == OAR_FreeOnFailure);
3710 }
3711 }
3712 }
3713 state = state->remove<ReallocPairs>(Sym);
3714 }
3715
3716 return state;
3717}
3718
3719bool MallocChecker::ignoreDirectEscapeTo(const CallEvent *Call,
3720 SymbolRef &EscapingSymbol) const {
3721 assert(Call);
3722 EscapingSymbol = nullptr;
3723
3724 // For now, assume that any C++ or block call can free memory.
3725 // TODO: If we want to be more optimistic here, we'll need to make sure that
3726 // regions escape to C++ containers. They seem to do that even now, but for
3727 // mysterious reasons.
3729 return false;
3730
3731 // Check Objective-C messages by selector name.
3732 if (const ObjCMethodCall *Msg = dyn_cast<ObjCMethodCall>(Call)) {
3733 // If it's not a framework call, or if it takes a callback, assume it
3734 // can free memory.
3735 if (!Call->isInSystemHeader() || Call->argumentsMayEscape())
3736 return false;
3737
3738 // If it's a method we know about, handle it explicitly post-call.
3739 // This should happen before the "freeWhenDone" check below.
3741 return true;
3742
3743 // If there's a "freeWhenDone" parameter, but the method isn't one we know
3744 // about, we can't be sure that the object will use free() to deallocate the
3745 // memory, so we can't model it explicitly. The best we can do is use it to
3746 // decide whether the pointer escapes.
3747 if (std::optional<bool> FreeWhenDone = getFreeWhenDoneArg(*Msg))
3748 return !*FreeWhenDone;
3749
3750 // If the first selector piece ends with "NoCopy", and there is no
3751 // "freeWhenDone" parameter set to zero, we know ownership is being
3752 // transferred. Again, though, we can't be sure that the object will use
3753 // free() to deallocate the memory, so we can't model it explicitly.
3754 StringRef FirstSlot = Msg->getSelector().getNameForSlot(0);
3755 if (FirstSlot.ends_with("NoCopy"))
3756 return false;
3757
3758 // If the first selector starts with addPointer, insertPointer,
3759 // or replacePointer, assume we are dealing with NSPointerArray or similar.
3760 // This is similar to C++ containers (vector); we still might want to check
3761 // that the pointers get freed by following the container itself.
3762 if (FirstSlot.starts_with("addPointer") ||
3763 FirstSlot.starts_with("insertPointer") ||
3764 FirstSlot.starts_with("replacePointer") ||
3765 FirstSlot == "valueWithPointer") {
3766 return false;
3767 }
3768
3769 // We should escape receiver on call to 'init'. This is especially relevant
3770 // to the receiver, as the corresponding symbol is usually not referenced
3771 // after the call.
3772 if (Msg->getMethodFamily() == OMF_init) {
3773 EscapingSymbol = Msg->getReceiverSVal().getAsSymbol();
3774 return false;
3775 }
3776
3777 // Otherwise, assume that the method does not free memory.
3778 // Most framework methods do not free memory.
3779 return true;
3780 }
3781
3782 // At this point the only thing left to handle is straight function calls.
3783 const FunctionDecl *FD = cast<SimpleFunctionCall>(Call)->getDecl();
3784 if (!FD)
3785 return false;
3786
3787 // If it's not a system call, assume it frees memory.
3788 if (!Call->isInSystemHeader())
3789 return false;
3790
3791 // White list the system functions whose arguments escape.
3792 const IdentifierInfo *II = FD->getIdentifier();
3793 if (!II)
3794 return false;
3795 StringRef FName = II->getName();
3796
3797 // White list the 'XXXNoCopy' CoreFoundation functions.
3798 // We specifically check these before
3799 if (FName.ends_with("NoCopy")) {
3800 // Look for the deallocator argument. We know that the memory ownership
3801 // is not transferred only if the deallocator argument is
3802 // 'kCFAllocatorNull'.
3803 for (unsigned i = 1; i < Call->getNumArgs(); ++i) {
3804 const Expr *ArgE = Call->getArgExpr(i)->IgnoreParenCasts();
3805 if (const DeclRefExpr *DE = dyn_cast<DeclRefExpr>(ArgE)) {
3806 StringRef DeallocatorName = DE->getFoundDecl()->getName();
3807 if (DeallocatorName == "kCFAllocatorNull")
3808 return true;
3809 }
3810 }
3811 return false;
3812 }
3813
3814 // Associating streams with malloced buffers. The pointer can escape if
3815 // 'closefn' is specified (and if that function does free memory),
3816 // but it will not if closefn is not specified.
3817 // Currently, we do not inspect the 'closefn' function (PR12101).
3818 if (FName == "funopen")
3819 if (Call->getNumArgs() >= 5 && Call->getArgSVal(4).isConstant(0))
3820 return true;
3821
3822 // Do not warn on pointers passed to 'setbuf' when used with std streams,
3823 // these leaks might be intentional when setting the buffer for stdio.
3824 // http://stackoverflow.com/questions/2671151/who-frees-setvbuf-buffer
3825 if (FName == "setbuf" || FName =="setbuffer" ||
3826 FName == "setlinebuf" || FName == "setvbuf") {
3827 if (Call->getNumArgs() >= 1) {
3828 const Expr *ArgE = Call->getArgExpr(0)->IgnoreParenCasts();
3829 if (const DeclRefExpr *ArgDRE = dyn_cast<DeclRefExpr>(ArgE))
3830 if (const VarDecl *D = dyn_cast<VarDecl>(ArgDRE->getDecl()))
3831 if (D->getCanonicalDecl()->getName().contains("std"))
3832 return false;
3833 }
3834 }
3835
3836 // A bunch of other functions which either take ownership of a pointer or
3837 // wrap the result up in a struct or object, meaning it can be freed later.
3838 // (See RetainCountChecker.) Not all the parameters here are invalidated,
3839 // but the Malloc checker cannot differentiate between them. The right way
3840 // of doing this would be to implement a pointer escapes callback.
3841 if (FName == "CGBitmapContextCreate" ||
3842 FName == "CGBitmapContextCreateWithData" ||
3843 FName == "CVPixelBufferCreateWithBytes" ||
3844 FName == "CVPixelBufferCreateWithPlanarBytes" ||
3845 FName == "OSAtomicEnqueue") {
3846 return false;
3847 }
3848
3849 if (FName == "postEvent" &&
3850 FD->getQualifiedNameAsString() == "QCoreApplication::postEvent") {
3851 return false;
3852 }
3853
3854 if (FName == "connectImpl" &&
3855 FD->getQualifiedNameAsString() == "QObject::connectImpl") {
3856 return false;
3857 }
3858
3859 if (FName == "singleShotImpl" &&
3860 FD->getQualifiedNameAsString() == "QTimer::singleShotImpl") {
3861 return false;
3862 }
3863
3864 // Protobuf function declared in `generated_message_util.h` that takes
3865 // ownership of the second argument. As the first and third arguments are
3866 // allocation arenas and won't be tracked by this checker, there is no reason
3867 // to set `EscapingSymbol`. (Also, this is an implementation detail of
3868 // Protobuf, so it's better to be a bit more permissive.)
3869 if (FName == "GetOwnedMessageInternal") {
3870 return false;
3871 }
3872
3873 // Handle cases where we know a buffer's /address/ can escape.
3874 // Note that the above checks handle some special cases where we know that
3875 // even though the address escapes, it's still our responsibility to free the
3876 // buffer.
3877 if (Call->argumentsMayEscape())
3878 return false;
3879
3880 // Otherwise, assume that the function does not free memory.
3881 // Most system calls do not free the memory.
3882 return true;
3883}
3884
3885ProgramStateRef MallocChecker::checkPointerEscape(ProgramStateRef State,
3886 const InvalidatedSymbols &Escaped,
3887 const CallEvent *Call,
3888 PointerEscapeKind Kind) const {
3889 return checkPointerEscapeAux(State, Escaped, Call, Kind,
3890 /*IsConstPointerEscape*/ false);
3891}
3892
3893ProgramStateRef MallocChecker::checkConstPointerEscape(ProgramStateRef State,
3894 const InvalidatedSymbols &Escaped,
3895 const CallEvent *Call,
3896 PointerEscapeKind Kind) const {
3897 // If a const pointer escapes, it may not be freed(), but it could be deleted.
3898 return checkPointerEscapeAux(State, Escaped, Call, Kind,
3899 /*IsConstPointerEscape*/ true);
3900}
3901
3902static bool checkIfNewOrNewArrayFamily(const RefState *RS) {
3903 return (RS->getAllocationFamily().Kind == AF_CXXNewArray ||
3904 RS->getAllocationFamily().Kind == AF_CXXNew);
3905}
3906
3907ProgramStateRef MallocChecker::checkPointerEscapeAux(
3908 ProgramStateRef State, const InvalidatedSymbols &Escaped,
3909 const CallEvent *Call, PointerEscapeKind Kind,
3910 bool IsConstPointerEscape) const {
3911 SymbolRef EscapingSymbol = nullptr;
3912 if (Kind == PSK_DirectEscapeOnCall) {
3913 // If we want to model this call explicitly, don't discard state.
3914 // FIXME: Maybe extend this to non-direct escape and/or non-simple calls?
3915 // ('isMemCall' is true for e.g. a C++ method with ownership attributes.)
3916 if (isa<SimpleFunctionCall>(Call) && isMemCall(*Call))
3917 return State;
3918 // If we know that the call cannot release memory, don't discard state.
3919 if (ignoreDirectEscapeTo(Call, EscapingSymbol))
3920 return State;
3921 }
3922
3923 for (SymbolRef sym : Escaped) {
3924 if (EscapingSymbol && EscapingSymbol != sym)
3925 continue;
3926
3927 if (const RefState *RS = State->get<RegionState>(sym))
3928 if (RS->isAllocated())
3929 if (!IsConstPointerEscape || checkIfNewOrNewArrayFamily(RS))
3930 State = State->set<RegionState>(sym, RefState::getEscaped(RS));
3931 }
3932 return State;
3933}
3934
3935bool MallocChecker::isArgZERO_SIZE_PTR(ProgramStateRef State, CheckerContext &C,
3936 SVal ArgVal) const {
3937 if (!KernelZeroSizePtrValue)
3938 KernelZeroSizePtrValue =
3939 tryExpandAsInteger("ZERO_SIZE_PTR", C.getPreprocessor());
3940
3941 const llvm::APSInt *ArgValKnown =
3942 C.getSValBuilder().getKnownValue(State, ArgVal);
3943 return ArgValKnown && *KernelZeroSizePtrValue &&
3944 ArgValKnown->getSExtValue() == **KernelZeroSizePtrValue;
3945}
3946
3948 ProgramStateRef prevState) {
3949 ReallocPairsTy currMap = currState->get<ReallocPairs>();
3950 ReallocPairsTy prevMap = prevState->get<ReallocPairs>();
3951
3952 for (const ReallocPairsTy::value_type &Pair : prevMap) {
3953 SymbolRef sym = Pair.first;
3954 if (!currMap.lookup(sym))
3955 return sym;
3956 }
3957
3958 return nullptr;
3959}
3960
3962 if (const IdentifierInfo *II = DD->getParent()->getIdentifier()) {
3963 StringRef N = II->getName();
3964 if (N.contains_insensitive("ptr") || N.contains_insensitive("pointer")) {
3965 if (N.contains_insensitive("ref") || N.contains_insensitive("cnt") ||
3966 N.contains_insensitive("intrusive") ||
3967 N.contains_insensitive("shared") || N.ends_with_insensitive("rc")) {
3968 return true;
3969 }
3970 }
3971 }
3972 return false;
3973}
3974
3975PathDiagnosticPieceRef MallocBugVisitor::VisitNode(const ExplodedNode *N,
3976 BugReporterContext &BRC,
3977 PathSensitiveBugReport &BR) {
3978 ProgramStateRef state = N->getState();
3979 ProgramStateRef statePrev = N->getFirstPred()->getState();
3980
3981 const RefState *RSCurr = state->get<RegionState>(Sym);
3982 const RefState *RSPrev = statePrev->get<RegionState>(Sym);
3983
3984 const Stmt *S = N->getStmtForDiagnostics();
3985 // When dealing with containers, we sometimes want to give a note
3986 // even if the statement is missing.
3987 if (!S && (!RSCurr || RSCurr->getAllocationFamily().Kind != AF_InnerBuffer))
3988 return nullptr;
3989
3990 const StackFrame *CurrentSF = N->getStackFrame();
3991
3992 // If we find an atomic fetch_add or fetch_sub within the function in which
3993 // the pointer was released (before the release), this is likely a release
3994 // point of reference-counted object (like shared pointer).
3995 //
3996 // Because we don't model atomics, and also because we don't know that the
3997 // original reference count is positive, we should not report use-after-frees
3998 // on objects deleted in such functions. This can probably be improved
3999 // through better shared pointer modeling.
4000 if (ReleaseFunctionSF && (ReleaseFunctionSF == CurrentSF ||
4001 ReleaseFunctionSF->isParentOf(CurrentSF))) {
4002 if (const auto *AE = dyn_cast<AtomicExpr>(S)) {
4003 // Check for manual use of atomic builtins.
4004 AtomicExpr::AtomicOp Op = AE->getOp();
4005 if (Op == AtomicExpr::AO__c11_atomic_fetch_add ||
4006 Op == AtomicExpr::AO__c11_atomic_fetch_sub) {
4007 BR.markInvalid(getTag(), S);
4008 // After report is considered invalid there is no need to proceed
4009 // futher.
4010 return nullptr;
4011 }
4012 } else if (const auto *CE = dyn_cast<CallExpr>(S)) {
4013 // Check for `std::atomic` and such. This covers both regular method calls
4014 // and operator calls.
4015 if (const auto *MD =
4016 dyn_cast_or_null<CXXMethodDecl>(CE->getDirectCallee())) {
4017 const CXXRecordDecl *RD = MD->getParent();
4018 // A bit wobbly with ".contains()" because it may be like
4019 // "__atomic_base" or something.
4020 if (StringRef(RD->getNameAsString()).contains("atomic")) {
4021 BR.markInvalid(getTag(), S);
4022 // After report is considered invalid there is no need to proceed
4023 // futher.
4024 return nullptr;
4025 }
4026 }
4027 }
4028 }
4029
4030 // FIXME: We will eventually need to handle non-statement-based events
4031 // (__attribute__((cleanup))).
4032
4033 // Find out if this is an interesting point and what is the kind.
4034 StringRef Msg;
4035 std::unique_ptr<StackHintGeneratorForSymbol> StackHint = nullptr;
4036 SmallString<256> Buf;
4037 llvm::raw_svector_ostream OS(Buf);
4038
4039 if (Mode == Normal) {
4040 if (isAllocated(RSCurr, RSPrev, S)) {
4041 Msg = "Memory is allocated";
4042 StackHint = std::make_unique<StackHintGeneratorForSymbol>(
4043 Sym, "Returned allocated memory");
4044 } else if (isReleased(RSCurr, RSPrev, S)) {
4045 const auto Family = RSCurr->getAllocationFamily();
4046 switch (Family.Kind) {
4047 case AF_Alloca:
4048 case AF_Malloc:
4049 case AF_Custom:
4050 case AF_CXXNew:
4051 case AF_CXXNewArray:
4052 case AF_IfNameIndex:
4053 Msg = "Memory is released";
4054 StackHint = std::make_unique<StackHintGeneratorForSymbol>(
4055 Sym, "Returning; memory was released");
4056 break;
4057 case AF_InnerBuffer: {
4058 const MemRegion *ObjRegion =
4060 const auto *TypedRegion = cast<TypedValueRegion>(ObjRegion);
4061 QualType ObjTy = TypedRegion->getValueType();
4062 OS << "Inner buffer of '" << ObjTy << "' ";
4063
4065 OS << "deallocated by call to destructor";
4066 StackHint = std::make_unique<StackHintGeneratorForSymbol>(
4067 Sym, "Returning; inner buffer was deallocated");
4068 } else {
4069 OS << "reallocated by call to '";
4070 const Stmt *S = RSCurr->getStmt();
4071 if (const auto *MemCallE = dyn_cast<CXXMemberCallExpr>(S)) {
4072 OS << MemCallE->getMethodDecl()->getDeclName();
4073 } else if (const auto *OpCallE = dyn_cast<CXXOperatorCallExpr>(S)) {
4074 OS << OpCallE->getDirectCallee()->getDeclName();
4075 } else if (const auto *CallE = dyn_cast<CallExpr>(S)) {
4076 auto &CEMgr = BRC.getStateManager().getCallEventManager();
4077 CallEventRef<> Call =
4078 CEMgr.getSimpleCall(CallE, state, CurrentSF, {nullptr, 0});
4079 if (const auto *D = dyn_cast_or_null<NamedDecl>(Call->getDecl()))
4080 OS << D->getDeclName();
4081 else
4082 OS << "unknown";
4083 }
4084 OS << "'";
4085 StackHint = std::make_unique<StackHintGeneratorForSymbol>(
4086 Sym, "Returning; inner buffer was reallocated");
4087 }
4088 Msg = OS.str();
4089 break;
4090 }
4091 case AF_None:
4092 assert(false && "Unhandled allocation family!");
4093 return nullptr;
4094 }
4095
4096 // Record the stack frame that is _responsible_ for this memory release
4097 // event. This will be used by the false positive suppression heuristics
4098 // that recognize the release points of reference-counted objects.
4099 //
4100 // Usually (e.g. in C) we say that the _responsible_ stack frame is the
4101 // current innermost stack frame:
4102 ReleaseFunctionSF = CurrentSF;
4103 // ...but if the stack contains a destructor call, then we say that the
4104 // outermost destructor stack frame is the _responsible_ one:
4105 for (const StackFrame &SF : N->stackframes()) {
4106 if (const auto *DD = dyn_cast<CXXDestructorDecl>(SF.getDecl())) {
4108 // This immediately looks like a reference-counting destructor.
4109 // We're bad at guessing the original reference count of the
4110 // object, so suppress the report for now.
4111 BR.markInvalid(getTag(), DD);
4112
4113 // After report is considered invalid there is no need to proceed
4114 // futher.
4115 return nullptr;
4116 }
4117
4118 // Switch suspection to outer destructor to catch patterns like:
4119 // (note that class name is distorted to bypass
4120 // isReferenceCountingPointerDestructor() logic)
4121 //
4122 // SmartPointr::~SmartPointr() {
4123 // if (refcount.fetch_sub(1) == 1)
4124 // release_resources();
4125 // }
4126 // void SmartPointr::release_resources() {
4127 // free(buffer);
4128 // }
4129 //
4130 // This way ReleaseFunctionSF will point to outermost destructor and
4131 // it would be possible to catch wider range of FP.
4132 //
4133 // NOTE: it would be great to support smth like that in C, since
4134 // currently patterns like following won't be supressed:
4135 //
4136 // void doFree(struct Data *data) { free(data); }
4137 // void putData(struct Data *data)
4138 // {
4139 // if (refPut(data))
4140 // doFree(data);
4141 // }
4142 ReleaseFunctionSF = &SF;
4143 }
4144 }
4145
4146 } else if (isRelinquished(RSCurr, RSPrev, S)) {
4147 Msg = "Memory ownership is transferred";
4148 StackHint = std::make_unique<StackHintGeneratorForSymbol>(Sym, "");
4149 } else if (hasReallocFailed(RSCurr, RSPrev, S)) {
4150 Mode = ReallocationFailed;
4151 Msg = "Reallocation failed";
4152 StackHint = std::make_unique<StackHintGeneratorForReallocationFailed>(
4153 Sym, "Reallocation failed");
4154
4155 if (SymbolRef sym = findFailedReallocSymbol(state, statePrev)) {
4156 // Is it possible to fail two reallocs WITHOUT testing in between?
4157 assert((!FailedReallocSymbol || FailedReallocSymbol == sym) &&
4158 "We only support one failed realloc at a time.");
4159 BR.markInteresting(sym);
4160 FailedReallocSymbol = sym;
4161 }
4162 }
4163
4164 // We are in a special mode if a reallocation failed later in the path.
4165 } else if (Mode == ReallocationFailed) {
4166 assert(FailedReallocSymbol && "No symbol to look for.");
4167
4168 // Is this is the first appearance of the reallocated symbol?
4169 if (!statePrev->get<RegionState>(FailedReallocSymbol)) {
4170 // We're at the reallocation point.
4171 Msg = "Attempt to reallocate memory";
4172 StackHint = std::make_unique<StackHintGeneratorForSymbol>(
4173 Sym, "Returned reallocated memory");
4174 FailedReallocSymbol = nullptr;
4175 Mode = Normal;
4176 }
4177 }
4178
4179 if (Msg.empty()) {
4180 assert(!StackHint);
4181 return nullptr;
4182 }
4183
4184 assert(StackHint);
4185
4186 // Generate the extra diagnostic.
4187 PathDiagnosticLocation Pos;
4188 if (!S) {
4189 assert(RSCurr->getAllocationFamily().Kind == AF_InnerBuffer);
4190 auto PostImplCall = N->getLocation().getAs<PostImplicitCall>();
4191 if (!PostImplCall)
4192 return nullptr;
4193 Pos = PathDiagnosticLocation(PostImplCall->getLocation(),
4194 BRC.getSourceManager());
4195 } else {
4196 Pos = PathDiagnosticLocation(S, BRC.getSourceManager(), N->getStackFrame());
4197 }
4198
4199 auto P = std::make_shared<PathDiagnosticEventPiece>(Pos, Msg, true);
4200 BR.addCallStackHint(P, std::move(StackHint));
4201 return P;
4202}
4203
4204void MallocChecker::printState(raw_ostream &Out, ProgramStateRef State,
4205 const char *NL, const char *Sep) const {
4206
4207 RegionStateTy RS = State->get<RegionState>();
4208
4209 if (!RS.isEmpty()) {
4210 Out << Sep << "MallocChecker :" << NL;
4211 for (auto [Sym, Data] : RS) {
4212 const RefState *RefS = State->get<RegionState>(Sym);
4213 AllocationFamily Family = RefS->getAllocationFamily();
4214
4215 const CheckerFrontend *Frontend =
4216 getRelevantFrontendAs<CheckerFrontend>(Family);
4217
4218 Sym->dumpToStream(Out);
4219 Out << " : ";
4220 Data.dump(Out);
4221 if (Frontend && Frontend->isEnabled())
4222 Out << " (" << Frontend->getName() << ")";
4223 Out << NL;
4224 }
4225 }
4226}
4227
4228namespace clang {
4229namespace ento {
4230namespace allocation_state {
4231
4233markReleased(ProgramStateRef State, SymbolRef Sym, const Expr *Origin) {
4234 AllocationFamily Family(AF_InnerBuffer);
4235 return State->set<RegionState>(Sym, RefState::getReleased(Family, Origin));
4236}
4237
4238} // end namespace allocation_state
4239} // end namespace ento
4240} // end namespace clang
4241
4242// Intended to be used in InnerPointerChecker to register the part of
4243// MallocChecker connected to it.
4245 Mgr.getChecker<MallocChecker>()->InnerPointerChecker.enable(Mgr);
4246}
4247
4248void ento::registerDynamicMemoryModeling(CheckerManager &Mgr) {
4249 auto *Chk = Mgr.getChecker<MallocChecker>();
4250 // FIXME: This is a "hidden" undocumented frontend but there are public
4251 // checker options which are attached to it.
4252 CheckerNameRef DMMName = Mgr.getCurrentCheckerName();
4253 Chk->ShouldIncludeOwnershipAnnotatedFunctions =
4254 Mgr.getAnalyzerOptions().getCheckerBooleanOption(DMMName, "Optimistic");
4255 Chk->ShouldRegisterNoOwnershipChangeVisitor =
4256 Mgr.getAnalyzerOptions().getCheckerBooleanOption(
4257 DMMName, "AddNoOwnershipChangeNotes");
4258 Chk->ModelAllocationFailure =
4259 Mgr.getAnalyzerOptions().getCheckerBooleanOption(
4260 DMMName, "ModelAllocationFailure");
4261}
4262
4263bool ento::shouldRegisterDynamicMemoryModeling(const CheckerManager &mgr) {
4264 return true;
4265}
4266
4267#define REGISTER_CHECKER(NAME) \
4268 void ento::register##NAME(CheckerManager &Mgr) { \
4269 Mgr.getChecker<MallocChecker>()->NAME.enable(Mgr); \
4270 } \
4271 \
4272 bool ento::shouldRegister##NAME(const CheckerManager &) { return true; }
4273
4274// TODO: NewDelete and NewDeleteLeaks shouldn't be registered when not in C++.
4275REGISTER_CHECKER(MallocChecker)
4276REGISTER_CHECKER(NewDeleteChecker)
4277REGISTER_CHECKER(NewDeleteLeaksChecker)
4278REGISTER_CHECKER(MismatchedDeallocatorChecker)
4279REGISTER_CHECKER(TaintedAllocChecker)
4280
4281#undef REGISTER_CHECKER
#define V(N, I)
#define REGISTER_CHECKER(name)
static void dump(llvm::raw_ostream &OS, StringRef FunctionName, ArrayRef< CounterExpression > Expressions, ArrayRef< CounterMappingRegion > Regions)
Defines the C++ Decl subclasses, other than those for templates (found in DeclTemplate....
Defines the C++ template declaration subclasses.
Defines the clang::Expr interface and subclasses for C++ expressions.
Result
Implement __builtin_bit_cast and related operations.
#define X(type, name)
Definition Value.h:97
Forward-declares and imports various common LLVM datatypes that clang wants to use unqualified.
llvm::MachO::Target Target
Definition MachO.h:51
static bool isRvalueByValueRecordWithSmartPtr(const Expr *AE)
Check if an expression is an rvalue record with smart owning pointer fields passed by value.
static bool isFromStdNamespace(const CallEvent &Call)
static bool isStandardNew(const FunctionDecl *FD)
static bool hasNonTrivialConstructorCall(const CXXNewExpr *NE)
static QualType getDeepPointeeType(QualType T)
static bool isReleased(SymbolRef Sym, CheckerContext &C)
Check if the memory associated with this symbol was released.
static void printExpectedAllocName(raw_ostream &os, AllocationFamily Family)
Print expected name of an allocator based on the deallocator's family derived from the DeallocExpr.
static void collectSmartPtrFieldRegions(const MemRegion *Reg, QualType RecQT, CheckerContext &C, llvm::SmallPtrSetImpl< const MemRegion * > &Out)
Collect memory regions of smart owning pointer fields from a record type (including fields from base ...
static bool hasSmartPtrField(const CXXRecordDecl *CRD, std::optional< FieldConsumer > FC=std::nullopt)
Check if a record type has smart owning pointer fields (directly or in base classes).
static bool isStandardDelete(const FunctionDecl *FD)
static bool isReferenceCountingPointerDestructor(const CXXDestructorDecl *DD)
static bool isSmartPtrType(QualType QT)
static bool isStandardNewDelete(const T &FD)
Tells if the callee is one of the builtin new/delete operators, including placement operators and oth...
static SymbolRef findFailedReallocSymbol(ProgramStateRef currState, ProgramStateRef prevState)
static bool isRvalueByValueRecord(const Expr *AE)
Check if an expression is an rvalue record type passed by value.
#define BUGTYPE_PROVIDER(NAME, DEF)
static bool isGRealloc(const CallEvent &Call)
static const Expr * getPlacementNewBufferArg(const CallExpr *CE, const FunctionDecl *FD)
#define CASE(ID)
static bool isSmartPtrRecord(const CXXRecordDecl *RD)
Check if a CXXRecordDecl has a name matching recognized smart pointer names.
#define CHECK_FN(NAME)
static void printExpectedDeallocName(raw_ostream &os, AllocationFamily Family)
Print expected name of a deallocator based on the allocator's family.
static bool isStandardRealloc(const CallEvent &Call)
static bool isSmartPtrCall(const CallEvent &Call)
Check if a call is a constructor of a smart owning pointer class that accepts pointer parameters.
static bool didPreviousFreeFail(ProgramStateRef State, SymbolRef Sym, SymbolRef &RetStatusSymbol)
Checks if the previous call to free on the given symbol failed - if free failed, returns true.
static ProgramStateRef MallocUpdateRefState(CheckerContext &C, const Expr *E, ProgramStateRef State, AllocationFamily Family, std::optional< SVal > RetVal=std::nullopt)
Update the RefState to reflect the new memory allocation.
static bool printMemFnName(raw_ostream &os, CheckerContext &C, const Expr *E)
Print names of allocators and deallocators.
static bool isSmartPtrName(StringRef Name)
static void printOwnershipTakesList(raw_ostream &os, CheckerContext &C, const Expr *E)
static bool isKnownDeallocObjCMethodName(const ObjCMethodCall &Call)
static std::optional< bool > getFreeWhenDoneArg(const ObjCMethodCall &Call)
static bool checkIfNewOrNewArrayFamily(const RefState *RS)
#define REGISTER_MAP_WITH_PROGRAMSTATE(Name, Key, Value)
Declares an immutable map of type NameTy, suitable for placement into the ProgramState.
#define REGISTER_SET_WITH_PROGRAMSTATE(Name, Elem)
Declares an immutable set of type NameTy, suitable for placement into the ProgramState.
Defines the SourceManager interface.
__DEVICE__ long long abs(long long __n)
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition ASTContext.h:246
SourceManager & getSourceManager()
Definition ASTContext.h:923
CanQualType VoidPtrTy
CanQualType getCanonicalSizeType() const
CanQualType UnsignedLongTy
CanQualType CharTy
static bool hasSameType(QualType T1, QualType T2)
Determine whether the given types T1 and T2 are equivalent.
QualType getSizeType() const
Return the unique type for "size_t" (C99 7.17), defined in <stddef.h>.
const TargetInfo & getTargetInfo() const
Definition ASTContext.h:981
bool hasCaptures() const
True if this block (or its nested blocks) captures anything of local storage from its enclosing scope...
Definition Decl.h:4984
const BlockDecl * getBlockDecl() const
Definition Expr.h:6770
Represents a base class of a C++ class.
Definition DeclCXX.h:146
Represents binding an expression to a temporary.
Definition ExprCXX.h:1498
Represents a call to a C++ constructor.
Definition ExprCXX.h:1553
CXXConstructorDecl * getConstructor() const
Get the constructor that this expression will (ultimately) call.
Definition ExprCXX.h:1616
Represents a C++ constructor within a class.
Definition DeclCXX.h:2645
Represents a delete expression for memory deallocation and destructor calls, e.g.
Definition ExprCXX.h:2631
bool isArrayForm() const
Definition ExprCXX.h:2657
Represents a C++ destructor within a class.
Definition DeclCXX.h:2924
const CXXRecordDecl * getParent() const
Return the parent of this method declaration, which is the class in which this method is defined.
Definition DeclCXX.h:2296
Represents a new-expression for memory allocation and constructor calls, e.g: "new CXXNewExpr(foo)".
Definition ExprCXX.h:2360
Represents a C++ struct/union/class.
Definition DeclCXX.h:258
base_class_range bases()
Definition DeclCXX.h:609
Represents a C++ functional cast expression that builds a temporary object.
Definition ExprCXX.h:1904
CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
Definition Expr.h:3012
Expr * getArg(unsigned Arg)
getArg - Return the specified argument.
Definition Expr.h:3216
FunctionDecl * getDirectCallee()
If the callee is a FunctionDecl, return it. Otherwise return null.
Definition Expr.h:3195
unsigned getNumArgs() const
getNumArgs - Return the number of actual arguments to this call.
Definition Expr.h:3203
static CharSourceRange getTokenRange(SourceRange R)
Decl - This represents one declaration (or definition), e.g.
Definition DeclBase.h:86
bool isInStdNamespace() const
Definition DeclBase.cpp:453
bool hasAttrs() const
Definition DeclBase.h:528
ASTContext & getASTContext() const LLVM_READONLY
Definition DeclBase.cpp:550
llvm::iterator_range< specific_attr_iterator< T > > specific_attrs() const
Definition DeclBase.h:569
SourceLocation getLocation() const
Definition DeclBase.h:449
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Decl.h:833
This represents one expression.
Definition Expr.h:114
bool isGLValue() const
Definition Expr.h:289
Expr * IgnoreParenCasts() LLVM_READONLY
Skip past any parentheses and casts which might surround this expression until reaching a fixed point...
Definition Expr.cpp:3135
Expr * IgnoreParenImpCasts() LLVM_READONLY
Skip past any parentheses and implicit casts which might surround this expression until reaching a fi...
Definition Expr.cpp:3130
QualType getType() const
Definition Expr.h:146
Represents a member of a struct/union/class.
Definition Decl.h:3346
Represents a function declaration or definition.
Definition Decl.h:2082
const ParmVarDecl * getParamDecl(unsigned i) const
Definition Decl.h:2979
Stmt * getBody(const FunctionDecl *&Definition) const
Retrieve the body (definition) of the function.
Definition Decl.cpp:3287
ArrayRef< ParmVarDecl * > parameters() const
Definition Decl.h:2952
bool isOverloadedOperator() const
Whether this function declaration represents an C++ overloaded operator, e.g., "operator+".
Definition Decl.h:3115
OverloadedOperatorKind getOverloadedOperator() const
getOverloadedOperator - Which C++ overloaded operator this function represents, if any.
Definition Decl.cpp:4218
QualType getDeclaredReturnType() const
Get the declared return type, which may differ from the actual return type if the return type is dedu...
Definition Decl.h:3044
bool hasBody(const FunctionDecl *&Definition) const
Returns true if the function has a body.
Definition Decl.cpp:3207
One of these records is kept for each identifier that is lexed.
StringRef getName() const
Return the actual identifier string.
ImplicitCastExpr - Allows us to explicitly represent implicit type conversions, which have no direct ...
Definition Expr.h:3922
Describes an C or C++ initializer list.
Definition Expr.h:5377
static StringRef getSourceText(CharSourceRange Range, const SourceManager &SM, const LangOptions &LangOpts, bool *Invalid=nullptr)
Returns a string for the source that the range encompasses.
Definition Lexer.cpp:1075
Represents a prvalue temporary that is written into memory so that a reference can bind to it.
Definition ExprCXX.h:4974
IdentifierInfo * getIdentifier() const
Get the identifier that names this declaration, if there is one.
Definition Decl.h:297
StringRef getName() const
Get the name of identifier for this declaration as a StringRef.
Definition Decl.h:303
std::string getQualifiedNameAsString() const
Definition Decl.cpp:1685
std::string getNameAsString() const
Get a human-readable name for the declaration, even if it is one of the special kinds of names (C++ c...
Definition Decl.h:319
An expression that sends a message to the given Objective-C object or class.
Definition ExprObjC.h:972
bool isConsumedExpr(Expr *E) const
Kind getKind() const
std::optional< T > getAs() const
Convert to the specified ProgramPoint type, returning std::nullopt if this ProgramPoint is not of the...
A (possibly-)qualified type.
Definition TypeBase.h:938
bool isNull() const
Return true if this QualType doesn't point to a type yet.
Definition TypeBase.h:1005
field_range fields() const
Definition Decl.h:4715
Expr * getRetValue()
Definition Stmt.h:3200
Smart pointer class that efficiently represents Objective-C method names.
StringRef getNameForSlot(unsigned argIndex) const
Retrieve the name at a given position in the selector.
unsigned getNumArgs() const
Encodes a location in the source.
bool isValid() const
Return true if this is a valid SourceLocation object.
bool isInSystemHeader(SourceLocation Loc) const
Returns if a SourceLocation is in a system header.
bool isParentOf(const StackFrame *SF) const
const Decl * getDecl() const
SourceRange getSourceRange() const LLVM_READONLY
SourceLocation tokens are not useful in isolation - they are low level value objects created/interpre...
Definition Stmt.cpp:343
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Stmt.cpp:355
const llvm::Triple & getTriple() const
Returns the target triple of the primary target.
The base class of all kinds of template declarations (e.g., class, function, etc.).
NamedDecl * getTemplatedDecl() const
Get the underlying, templated declaration.
CXXRecordDecl * getAsCXXRecordDecl() const
Retrieves the CXXRecordDecl that this type refers to, either because the type is a RecordType or beca...
Definition Type.h:26
bool isVoidPointerType() const
Definition Type.cpp:845
bool isFunctionPointerType() const
Definition TypeBase.h:8984
bool isPointerType() const
Definition TypeBase.h:8917
CanQualType getCanonicalTypeUnqualified() const
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
Definition Type.cpp:885
const T * getAs() const
Member-template getAs<specific type>'.
Definition TypeBase.h:9537
QualType getType() const
Definition Decl.h:725
bool isStaticLocal() const
Returns true if a variable with function scope is a static local variable.
Definition Decl.h:1216
APSIntPtr getMaxValue(const llvm::APSInt &v)
StringRef getDescription() const
A verbose warning message that is appropriate for displaying next to the source code that introduces ...
ProgramStateManager & getStateManager() const
const SourceManager & getSourceManager() const
BugReporterVisitors are used to add custom diagnostics along a path.
An immutable map from CallDescriptions to arbitrary data.
const T * lookup(const CallEvent &Call) const
CallEventRef getSimpleCall(const CallExpr *E, ProgramStateRef State, const StackFrame *SF, CFGBlock::ConstCFGElementRef ElemRef)
Represents an abstract call to a function or method along a particular path.
Definition CallEvent.h:151
Checker families (where a single backend class implements multiple related frontends) should derive f...
Definition Checker.h:596
A CheckerFrontend instance is what the user recognizes as "one checker": it has a public canonical na...
Definition Checker.h:526
CheckerNameRef getName() const
Definition Checker.h:536
const AnalyzerOptions & getAnalyzerOptions() const
CheckerNameRef getCurrentCheckerName() const
CHECKER * getChecker(AT &&...Args)
If the the singleton instance of a checker class is not yet constructed, then construct it (with the ...
This wrapper is used to ensure that only StringRefs originating from the CheckerRegistry are used as ...
bool isConstrainedTrue() const
Return true if the constraint is perfectly constrained to 'true'.
ConditionTruthVal isNull(ProgramStateRef State, SymbolRef Sym)
Convenience method to query the state to see if a symbol is null or not null, or if neither assumptio...
const ProgramStateRef & getState() const
const Stmt * getStmtForDiagnostics() const
If the node's program point corresponds to a statement, retrieve that statement.
ProgramPoint getLocation() const
getLocation - Returns the edge associated with the given node.
llvm::iterator_range< StackFrame::parent_iterator > stackframes() const
Iterates over the current stack frame and all of its ancestors.
ExplodedNode * getFirstPred()
const StackFrame * getStackFrame() const
static bool isLocType(QualType T)
Definition SVals.h:265
const VarRegion * getVarRegion(const VarDecl *VD, const StackFrame *SF)
getVarRegion - Retrieve or create the memory region associated with a specified VarDecl and StackFram...
MemRegion - The root abstract class for all memory regions.
Definition MemRegion.h:97
RegionOffset getAsOffset() const
Compute the offset within the top level memory object.
LLVM_ATTRIBUTE_RETURNS_NONNULL const MemSpaceRegion * getMemorySpace(ProgramStateRef State) const
Returns the most specific memory space for this memory region in the given ProgramStateRef.
LLVM_ATTRIBUTE_RETURNS_NONNULL const MemRegion * getBaseRegion() const
virtual void printPretty(raw_ostream &os) const
Print the region for use in diagnostics.
const RegionTy * getAs() const
Definition MemRegion.h:1427
Kind getKind() const
Definition MemRegion.h:203
virtual bool canPrintPretty() const
Returns true if this region can be printed in a user-friendly way.
Represents any expression that calls an Objective-C method.
Definition CallEvent.h:1225
static PathDiagnosticLocation createBegin(const Decl *D, const SourceManager &SM)
Create a location for the beginning of the declaration.
static PathDiagnosticLocation create(const Decl *D, const SourceManager &SM)
Create a location corresponding to the given declaration.
void markInteresting(SymbolRef sym, bugreporter::TrackingKind TKind=bugreporter::TrackingKind::Thorough)
Marks a symbol as interesting.
void addCallStackHint(PathDiagnosticPieceRef Piece, std::unique_ptr< StackHintGenerator > StackHint)
PathDiagnosticLocation getLocation() const override
The primary location of the bug report that points at the undesirable behavior in the code.
void markInvalid(const void *Tag, const void *Data)
Marks the current report as invalid, meaning that it is probably a false positive and should not be r...
CallEventManager & getCallEventManager()
bool hasSymbolicOffset() const
Definition MemRegion.h:82
int64_t getOffset() const
Definition MemRegion.h:84
DefinedOrUnknownSVal makeZeroVal(QualType type)
Construct an SVal representing '0' for the specified type.
BasicValueFactory & getBasicValueFactory()
ASTContext & getContext()
nonloc::ConcreteInt makeIntVal(const IntegerLiteral *integer)
virtual SVal evalBinOpNN(ProgramStateRef state, BinaryOperator::Opcode op, NonLoc lhs, NonLoc rhs, QualType resultTy)=0
Create a new value which represents a binary expression with two non- location operands.
QualType getConditionType() const
SVal evalEQ(ProgramStateRef state, SVal lhs, SVal rhs)
loc::MemRegionVal getAllocaRegionVal(const Expr *E, const StackFrame *SF, unsigned Count)
Create an SVal representing the result of an alloca()-like call, that is, an AllocaRegion on the stac...
DefinedSVal getConjuredHeapSymbolVal(ConstCFGElementRef elem, const StackFrame *SF, QualType type, unsigned Count)
Conjure a symbol representing heap allocated memory region.
SVal evalBinOp(ProgramStateRef state, BinaryOperator::Opcode op, SVal lhs, SVal rhs, QualType type)
SVal - This represents a symbolic expression, which can be either an L-value or an R-value.
Definition SVals.h:57
bool isUnknownOrUndef() const
Definition SVals.h:115
SymbolRef getAsSymbol(bool IncludeBaseRegions=false) const
If this SVal wraps a symbol return that SymbolRef.
Definition SVals.cpp:103
std::optional< T > getAs() const
Convert to the specified SVal type, returning std::nullopt if this SVal is not of the desired type.
Definition SVals.h:88
SymbolRef getAsLocSymbol(bool IncludeBaseRegions=false) const
If this SVal is a location and wraps a symbol, return that SymbolRef.
Definition SVals.cpp:67
const MemRegion * getAsRegion() const
Definition SVals.cpp:119
SymbolRef getLocSymbolInBase() const
Get the symbol in the SVal or its base region.
Definition SVals.cpp:79
T castAs() const
Convert to the specified SVal type, asserting that this SVal is of the desired type.
Definition SVals.h:84
SubRegion - A region that subsets another larger region.
Definition MemRegion.h:481
LLVM_ATTRIBUTE_RETURNS_NONNULL const MemRegion * getSuperRegion() const
Definition MemRegion.h:494
virtual void dumpToStream(raw_ostream &os) const
Definition SymExpr.h:86
virtual QualType getType() const =0
bool isDead(SymbolRef sym)
Returns whether or not a symbol has been confirmed dead.
SymbolRef getSymbol() const
It might return null.
Definition MemRegion.h:833
const VarDecl * getDecl() const override=0
const StackFrame * getStackFrame() const
It might return null.
Defines the clang::TargetInfo interface.
__inline void unsigned int _2
const internal::VariadicDynCastAllOfMatcher< Stmt, CXXDeleteExpr > cxxDeleteExpr
Matches delete expressions.
const internal::VariadicDynCastAllOfMatcher< Stmt, CallExpr > callExpr
Matches call expressions.
SmallVector< BoundNodes, 1 > match(MatcherT Matcher, const NodeT &Node, ASTContext &Context)
Returns the results of matching Matcher on Node.
internal::Matcher< T > findAll(const internal::Matcher< T > &Matcher)
Matches if the node or any descendant matches.
const internal::VariadicAllOfMatcher< Stmt > stmt
Matches statements.
const internal::VariadicOperatorMatcherFunc< 2, std::numeric_limits< unsigned >::max()> anyOf
Matches if any of the given matchers matches.
ProgramStateRef markReleased(ProgramStateRef State, SymbolRef Sym, const Expr *Origin)
std::unique_ptr< BugReporterVisitor > getInnerPointerBRVisitor(SymbolRef Sym)
This function provides an additional visitor that augments the bug report with information relevant t...
const MemRegion * getContainerObjRegion(ProgramStateRef State, SymbolRef Sym)
'Sym' represents a pointer to the inner buffer of a container object.
std::vector< SymbolRef > getTaintedSymbols(ProgramStateRef State, const Expr *E, const StackFrame *SF, TaintTagType Kind=TaintTagGeneric)
Returns the tainted Symbols for a given expression and state.
Definition Taint.cpp:169
PointerEscapeKind
Describes the different reasons a pointer escapes during analysis.
@ PSK_DirectEscapeOnCall
The pointer has been passed to a function call directly.
llvm::DenseSet< SymbolRef > InvalidatedSymbols
Definition Store.h:50
IntrusiveRefCntPtr< const ProgramState > ProgramStateRef
const SymExpr * SymbolRef
Definition SymExpr.h:166
ProgramStateRef setDynamicExtent(ProgramStateRef State, const MemRegion *MR, DefinedOrUnknownSVal Extent)
Set the dynamic extent Extent of the region MR.
void registerInnerPointerCheckerAux(CheckerManager &Mgr)
Register the part of MallocChecker connected to InnerPointerChecker.
@ OS
Indicates that the tracking object is a descendant of a referenced-counted OSObject,...
std::optional< SVal > getPointeeVal(SVal PtrSVal, ProgramStateRef State)
std::optional< int > tryExpandAsInteger(StringRef Macro, const Preprocessor &PP)
Try to parse the value of a defined preprocessor macro.
std::shared_ptr< PathDiagnosticPiece > PathDiagnosticPieceRef
bool NE(InterpState &S, CodePtr OpPC)
Definition Interp.h:1498
Top level wrappers for InstallAPI frontend operations.
OverloadedOperatorKind
Enumeration specifying the different kinds of C++ overloaded operators.
@ Match
This is not an overload because the signature exactly matches an existing declaration.
Definition Sema.h:824
bool isa(CodeGen::Address addr)
Definition Address.h:330
Stmt Stmt * Callback
Definition StmtOpenMP.h:930
bool operator==(const CallGraphNode::CallRecord &LHS, const CallGraphNode::CallRecord &RHS)
Definition CallGraph.h:218
nullptr
This class represents a compute construct, representing a 'Kind' of ‘parallel’, 'serial',...
bool operator!=(CanQual< T > x, CanQual< U > y)
const char * getOperatorSpelling(OverloadedOperatorKind Operator)
Retrieve the spelling of the given overloaded operator, without the preceding "operator" keyword.
U cast(CodeGen::Address addr)
Definition Address.h:327
int const char * function
Definition c++config.h:31
Helper struct for collecting smart owning pointer field regions.
void consume(const FieldDecl *FD)
std::optional< FieldConsumer > switchToBase(const CXXRecordDecl *BaseDecl, bool IsVirtual)
FieldConsumer(const MemRegion *Reg, CheckerContext &C, llvm::SmallPtrSetImpl< const MemRegion * > &Out)
llvm::SmallPtrSetImpl< const MemRegion * > * Out
CheckerContext * C
const MemRegion * Reg