clang 23.0.0git
BugReporterVisitors.cpp
Go to the documentation of this file.
1//===- BugReporterVisitors.cpp - Helpers for reporting bugs ---------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file defines a set of BugReporter "visitors" which can be used to
10// enhance the diagnostics reported for a bug.
11//
12//===----------------------------------------------------------------------===//
13
16#include "clang/AST/Decl.h"
17#include "clang/AST/DeclBase.h"
18#include "clang/AST/DeclCXX.h"
19#include "clang/AST/Expr.h"
20#include "clang/AST/ExprCXX.h"
21#include "clang/AST/ExprObjC.h"
22#include "clang/AST/Stmt.h"
23#include "clang/AST/Type.h"
27#include "clang/Analysis/CFG.h"
32#include "clang/Basic/LLVM.h"
35#include "clang/Lex/Lexer.h"
47#include "llvm/ADT/ArrayRef.h"
48#include "llvm/ADT/SmallPtrSet.h"
49#include "llvm/ADT/SmallString.h"
50#include "llvm/ADT/StringExtras.h"
51#include "llvm/ADT/StringRef.h"
52#include "llvm/Support/Casting.h"
53#include "llvm/Support/ErrorHandling.h"
54#include "llvm/Support/raw_ostream.h"
55#include <cassert>
56#include <memory>
57#include <optional>
58#include <stack>
59#include <string>
60#include <utility>
61
62using namespace clang;
63using namespace ento;
64using namespace bugreporter;
65
66//===----------------------------------------------------------------------===//
67// Utility functions.
68//===----------------------------------------------------------------------===//
69
71 if (B->isAdditiveOp() && B->getType()->isPointerType()) {
72 if (B->getLHS()->getType()->isPointerType()) {
73 return B->getLHS();
74 } else if (B->getRHS()->getType()->isPointerType()) {
75 return B->getRHS();
76 }
77 }
78 return nullptr;
79}
80
81/// \return A subexpression of @c Ex which represents the
82/// expression-of-interest.
83static const Expr *peelOffOuterExpr(const Expr *Ex, const ExplodedNode *N);
84
85/// Given that expression S represents a pointer that would be dereferenced,
86/// try to find a sub-expression from which the pointer came from.
87/// This is used for tracking down origins of a null or undefined value:
88/// "this is null because that is null because that is null" etc.
89/// We wipe away field and element offsets because they merely add offsets.
90/// We also wipe away all casts except lvalue-to-rvalue casts, because the
91/// latter represent an actual pointer dereference; however, we remove
92/// the final lvalue-to-rvalue cast before returning from this function
93/// because it demonstrates more clearly from where the pointer rvalue was
94/// loaded. Examples:
95/// x->y.z ==> x (lvalue)
96/// foo()->y.z ==> foo() (rvalue)
98 const auto *E = dyn_cast<Expr>(S);
99 if (!E)
100 return nullptr;
101
102 while (true) {
103 if (const auto *CE = dyn_cast<CastExpr>(E)) {
104 if (CE->getCastKind() == CK_LValueToRValue) {
105 // This cast represents the load we're looking for.
106 break;
107 }
108 E = CE->getSubExpr();
109 } else if (const auto *B = dyn_cast<BinaryOperator>(E)) {
110 // Pointer arithmetic: '*(x + 2)' -> 'x') etc.
111 if (const Expr *Inner = peelOffPointerArithmetic(B)) {
112 E = Inner;
113 } else if (B->isAssignmentOp()) {
114 // Follow LHS of assignments: '*p = 404' -> 'p'.
115 E = B->getLHS();
116 } else {
117 // Probably more arithmetic can be pattern-matched here,
118 // but for now give up.
119 break;
120 }
121 } else if (const auto *U = dyn_cast<UnaryOperator>(E)) {
122 if (U->getOpcode() == UO_Deref || U->getOpcode() == UO_AddrOf ||
123 (U->isIncrementDecrementOp() && U->getType()->isPointerType())) {
124 // Operators '*' and '&' don't actually mean anything.
125 // We look at casts instead.
126 E = U->getSubExpr();
127 } else {
128 // Probably more arithmetic can be pattern-matched here,
129 // but for now give up.
130 break;
131 }
132 }
133 // Pattern match for a few useful cases: a[0], p->f, *p etc.
134 else if (const auto *ME = dyn_cast<MemberExpr>(E)) {
135 // This handles the case when the dereferencing of a member reference
136 // happens. This is needed, because the AST for dereferencing a
137 // member reference looks like the following:
138 // |-MemberExpr
139 // `-DeclRefExpr
140 // Without this special case the notes would refer to the whole object
141 // (struct, class or union variable) instead of just the relevant member.
142
143 if (ME->getMemberDecl()->getType()->isReferenceType())
144 break;
145 E = ME->getBase();
146 } else if (const auto *IvarRef = dyn_cast<ObjCIvarRefExpr>(E)) {
147 E = IvarRef->getBase();
148 } else if (const auto *AE = dyn_cast<ArraySubscriptExpr>(E)) {
149 E = AE->getBase();
150 } else if (const auto *PE = dyn_cast<ParenExpr>(E)) {
151 E = PE->getSubExpr();
152 } else if (const auto *FE = dyn_cast<FullExpr>(E)) {
153 E = FE->getSubExpr();
154 } else {
155 // Other arbitrary stuff.
156 break;
157 }
158 }
159
160 // Special case: remove the final lvalue-to-rvalue cast, but do not recurse
161 // deeper into the sub-expression. This way we return the lvalue from which
162 // our pointer rvalue was loaded.
163 if (const auto *CE = dyn_cast<ImplicitCastExpr>(E))
164 if (CE->getCastKind() == CK_LValueToRValue)
165 E = CE->getSubExpr();
166
167 return E;
168}
169
170static const VarDecl *getVarDeclForExpression(const Expr *E) {
171 if (const auto *DR = dyn_cast<DeclRefExpr>(E))
172 return dyn_cast<VarDecl>(DR->getDecl());
173 return nullptr;
174}
175
176static const MemRegion *
178 bool LookingForReference = true) {
179 if (const auto *ME = dyn_cast<MemberExpr>(E)) {
180 // This handles null references from FieldRegions, for example:
181 // struct Wrapper { int &ref; };
182 // Wrapper w = { *(int *)0 };
183 // w.ref = 1;
184 const Expr *Base = ME->getBase();
186 if (!VD)
187 return nullptr;
188
189 const auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
190 if (!FD)
191 return nullptr;
192
193 if (FD->getType()->isReferenceType()) {
194 SVal StructSVal = N->getState()->getLValue(VD, N->getStackFrame());
195 return N->getState()->getLValue(FD, StructSVal).getAsRegion();
196 }
197 return nullptr;
198 }
199
200 const VarDecl *VD = getVarDeclForExpression(E);
201 if (!VD)
202 return nullptr;
203 if (LookingForReference && !VD->getType()->isReferenceType())
204 return nullptr;
205 return N->getState()->getLValue(VD, N->getStackFrame()).getAsRegion();
206}
207
208/// Comparing internal representations of symbolic values (via
209/// SVal::operator==()) is a valid way to check if the value was updated,
210/// unless it's a LazyCompoundVal that may have a different internal
211/// representation every time it is loaded from the state. In this function we
212/// do an approximate comparison for lazy compound values, checking that they
213/// are the immediate snapshots of the tracked region's bindings within the
214/// node's respective states but not really checking that these snapshots
215/// actually contain the same set of bindings.
216static bool hasVisibleUpdate(const ExplodedNode *LeftNode, SVal LeftVal,
217 const ExplodedNode *RightNode, SVal RightVal) {
218 if (LeftVal == RightVal)
219 return true;
220
221 const auto LLCV = LeftVal.getAs<nonloc::LazyCompoundVal>();
222 if (!LLCV)
223 return false;
224
225 const auto RLCV = RightVal.getAs<nonloc::LazyCompoundVal>();
226 if (!RLCV)
227 return false;
228
229 return LLCV->getRegion() == RLCV->getRegion() &&
230 LLCV->getStore() == LeftNode->getState()->getStore() &&
231 RLCV->getStore() == RightNode->getState()->getStore();
232}
233
234static std::optional<SVal> getSValForVar(const Expr *CondVarExpr,
235 const ExplodedNode *N) {
236 ProgramStateRef State = N->getState();
237 const StackFrame *SF = N->getStackFrame();
238
239 assert(CondVarExpr);
240 CondVarExpr = CondVarExpr->IgnoreImpCasts();
241
242 // The declaration of the value may rely on a pointer so take its l-value.
243 // FIXME: As seen in VisitCommonDeclRefExpr, sometimes DeclRefExpr may
244 // evaluate to a FieldRegion when it refers to a declaration of a lambda
245 // capture variable. We most likely need to duplicate that logic here.
246 if (const auto *DRE = dyn_cast<DeclRefExpr>(CondVarExpr))
247 if (const auto *VD = dyn_cast<VarDecl>(DRE->getDecl()))
248 return State->getSVal(State->getLValue(VD, SF));
249
250 if (const auto *ME = dyn_cast<MemberExpr>(CondVarExpr))
251 if (const auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
252 if (auto FieldL = State->getSVal(ME, SF).getAs<Loc>())
253 return State->getRawSVal(*FieldL, FD->getType());
254
255 return std::nullopt;
256}
257
258static std::optional<const llvm::APSInt *>
259getConcreteIntegerValue(const Expr *CondVarExpr, const ExplodedNode *N) {
260
261 if (std::optional<SVal> V = getSValForVar(CondVarExpr, N))
262 if (auto CI = V->getAs<nonloc::ConcreteInt>())
263 return CI->getValue().get();
264 return std::nullopt;
265}
266
267static bool isVarAnInterestingCondition(const Expr *CondVarExpr,
268 const ExplodedNode *N,
269 const PathSensitiveBugReport *B) {
270 // Even if this condition is marked as interesting, it isn't *that*
271 // interesting if it didn't happen in a nested stackframe, the user could just
272 // follow the arrows.
274 return false;
275
276 if (std::optional<SVal> V = getSValForVar(CondVarExpr, N))
277 if (std::optional<bugreporter::TrackingKind> K =
279 return *K == bugreporter::TrackingKind::Condition;
280
281 return false;
282}
283
284static bool isInterestingExpr(const Expr *E, const ExplodedNode *N,
285 const PathSensitiveBugReport *B) {
286 if (std::optional<SVal> V = getSValForVar(E, N))
287 return B->getInterestingnessKind(*V).has_value();
288 return false;
289}
290
291/// \return name of the macro inside the location \p Loc.
293 BugReporterContext &BRC) {
295 Loc,
296 BRC.getSourceManager(),
297 BRC.getASTContext().getLangOpts());
298}
299
300/// \return Whether given spelling location corresponds to an expansion
301/// of a function-like macro.
303 const SourceManager &SM) {
304 if (!Loc.isMacroID())
305 return false;
306 while (SM.isMacroArgExpansion(Loc))
307 Loc = SM.getImmediateExpansionRange(Loc).getBegin();
308 FileIDAndOffset TLInfo = SM.getDecomposedLoc(Loc);
309 SrcMgr::SLocEntry SE = SM.getSLocEntry(TLInfo.first);
310 const SrcMgr::ExpansionInfo &EInfo = SE.getExpansion();
311 return EInfo.isFunctionMacroExpansion();
312}
313
314/// \return Whether \c RegionOfInterest was modified at \p N,
315/// where \p ValueAfter is \c RegionOfInterest's value at the end of the
316/// stack frame.
317static bool wasRegionOfInterestModifiedAt(const SubRegion *RegionOfInterest,
318 const ExplodedNode *N,
319 SVal ValueAfter) {
320 ProgramStateRef State = N->getState();
321 ProgramStateManager &Mgr = N->getState()->getStateManager();
322
324 !N->getLocationAs<PostStmt>())
325 return false;
326
327 // Writing into region of interest.
328 if (auto PS = N->getLocationAs<PostStmt>())
329 if (auto *BO = PS->getStmtAs<BinaryOperator>())
330 if (BO->isAssignmentOp() && RegionOfInterest->isSubRegionOf(
331 N->getSVal(BO->getLHS()).getAsRegion()))
332 return true;
333
334 // SVal after the state is possibly different.
335 SVal ValueAtN = N->getState()->getSVal(RegionOfInterest);
336 if (!Mgr.getSValBuilder()
337 .areEqual(State, ValueAtN, ValueAfter)
339 (!ValueAtN.isUndef() || !ValueAfter.isUndef()))
340 return true;
341
342 return false;
343}
344
345//===----------------------------------------------------------------------===//
346// Implementation of BugReporterVisitor.
347//===----------------------------------------------------------------------===//
348
354
358
361 const ExplodedNode *EndPathNode,
362 const PathSensitiveBugReport &BR) {
364 const auto &Ranges = BR.getRanges();
365
366 // Only add the statement itself as a range if we didn't specify any
367 // special ranges for this report.
368 auto P = std::make_shared<PathDiagnosticEventPiece>(
369 L, BR.getDescription(), Ranges.begin() == Ranges.end());
370 for (SourceRange Range : Ranges)
371 P->addRange(Range);
372
373 return P;
374}
375
376//===----------------------------------------------------------------------===//
377// Implementation of NoStateChangeFuncVisitor.
378//===----------------------------------------------------------------------===//
379
380bool NoStateChangeFuncVisitor::isModifiedInFrame(const ExplodedNode *N) {
381 const StackFrame *SF = N->getStackFrame();
382 if (!FramesModifyingCalculated.count(SF))
383 findModifyingFrames(N);
384 return FramesModifying.count(SF);
385}
386
387void NoStateChangeFuncVisitor::markFrameAsModifying(const StackFrame *SF) {
388 while (!SF->inTopFrame()) {
389 auto p = FramesModifying.insert(SF);
390 if (!p.second)
391 break; // Frame and all its parents already inserted.
392
393 SF = SF->getParent();
394 }
395}
396
398 assert(N->getLocationAs<CallEnter>());
399 // The stackframe of the callee is only found in the nodes succeeding
400 // the CallEnter node. CallEnter's stack frame refers to the caller.
401 const StackFrame *OrigSF = N->getFirstSucc()->getStackFrame();
402
403 // Similarly, the nodes preceding CallExitEnd refer to the callee's stack
404 // frame.
405 auto IsMatchingCallExitEnd = [OrigSF](const ExplodedNode *N) {
406 return N->getLocationAs<CallExitEnd>() &&
407 OrigSF == N->getFirstPred()->getStackFrame();
408 };
409 while (N && !IsMatchingCallExitEnd(N)) {
410 assert(N->succ_size() <= 1 &&
411 "This function is to be used on the trimmed ExplodedGraph!");
412 N = N->getFirstSucc();
413 }
414 return N;
415}
416
417void NoStateChangeFuncVisitor::findModifyingFrames(
418 const ExplodedNode *const CallExitBeginN) {
419
420 assert(CallExitBeginN->getLocationAs<CallExitBegin>());
421
422 const StackFrame *const OriginalSF = CallExitBeginN->getStackFrame();
423
424 const ExplodedNode *CurrCallExitBeginN = CallExitBeginN;
425 const StackFrame *CurrentSF = OriginalSF;
426
427 for (const ExplodedNode *CurrN = CallExitBeginN; CurrN;
428 CurrN = CurrN->getFirstPred()) {
429 // Found a new inlined call.
430 if (CurrN->getLocationAs<CallExitBegin>()) {
431 CurrCallExitBeginN = CurrN;
432 CurrentSF = CurrN->getStackFrame();
433 FramesModifyingCalculated.insert(CurrentSF);
434 // We won't see a change in between two identical exploded nodes: skip.
435 continue;
436 }
437
438 if (auto CE = CurrN->getLocationAs<CallEnter>()) {
439 if (const ExplodedNode *CallExitEndN = getMatchingCallExitEnd(CurrN))
440 if (wasModifiedInFunction(CurrN, CallExitEndN))
441 markFrameAsModifying(CurrentSF);
442
443 // We exited this inlined call, lets actualize the stack frame.
444 CurrentSF = CurrN->getStackFrame();
445
446 // Stop calculating at the current function, but always regard it as
447 // modifying, so we can avoid notes like this:
448 // void f(Foo &F) {
449 // F.field = 0; // note: 0 assigned to 'F.field'
450 // // note: returning without writing to 'F.field'
451 // }
452 if (CE->getCalleeStackFrame() == OriginalSF) {
453 markFrameAsModifying(CurrentSF);
454 break;
455 }
456 }
457
458 if (wasModifiedBeforeCallExit(CurrN, CurrCallExitBeginN))
459 markFrameAsModifying(CurrentSF);
460 }
461}
462
465
466 const StackFrame *SF = N->getStackFrame();
467 ProgramStateRef State = N->getState();
468 auto CallExitLoc = N->getLocationAs<CallExitBegin>();
469
470 // No diagnostic if region was modified inside the frame.
471 if (!CallExitLoc || isModifiedInFrame(N))
472 return nullptr;
473
476
477 // Optimistically suppress uninitialized value bugs that result
478 // from system headers having a chance to initialize the value
479 // but failing to do so. It's too unlikely a system header's fault.
480 // It's much more likely a situation in which the function has a failure
481 // mode that the user decided not to check. If we want to hunt such
482 // omitted checks, we should provide an explicit function-specific note
483 // describing the precondition under which the function isn't supposed to
484 // initialize its out-parameter, and additionally check that such
485 // precondition can actually be fulfilled on the current path.
486 if (Call->isInSystemHeader()) {
487 // We make an exception for system header functions that have no branches.
488 // Such functions unconditionally fail to initialize the variable.
489 // If they call other functions that have more paths within them,
490 // this suppression would still apply when we visit these inner functions.
491 // One common example of a standard function that doesn't ever initialize
492 // its out parameter is operator placement new; it's up to the follow-up
493 // constructor (if any) to initialize the memory.
494 if (!N->getStackFrame()->getCFG()->isLinear()) {
495 static int i = 0;
496 R.markInvalid(&i, nullptr);
497 }
498 return nullptr;
499 }
500
501 if (const auto *MC = dyn_cast<ObjCMethodCall>(Call)) {
502 // If we failed to construct a piece for self, we still want to check
503 // whether the entity of interest is in a parameter.
505 return Piece;
506 }
507
508 if (const auto *CCall = dyn_cast<CXXConstructorCall>(Call)) {
509 // Do not generate diagnostics for not modified parameters in
510 // constructors.
511 return maybeEmitNoteForCXXThis(R, *CCall, N);
512 }
513
514 return maybeEmitNoteForParameters(R, *Call, N);
515}
516
517/// \return Whether the method declaration \p Parent
518/// syntactically has a binary operation writing into the ivar \p Ivar.
519static bool potentiallyWritesIntoIvar(const Decl *Parent,
520 const ObjCIvarDecl *Ivar) {
521 using namespace ast_matchers;
522 const char *IvarBind = "Ivar";
523 if (!Parent || !Parent->hasBody())
524 return false;
525 StatementMatcher WriteIntoIvarM = binaryOperator(
526 hasOperatorName("="),
527 hasLHS(ignoringParenImpCasts(
528 objcIvarRefExpr(hasDeclaration(equalsNode(Ivar))).bind(IvarBind))));
529 StatementMatcher ParentM = stmt(hasDescendant(WriteIntoIvarM));
530 auto Matches = match(ParentM, *Parent->getBody(), Parent->getASTContext());
531 for (BoundNodes &Match : Matches) {
532 auto IvarRef = Match.getNodeAs<ObjCIvarRefExpr>(IvarBind);
533 if (IvarRef->isFreeIvar())
534 return true;
535
536 const Expr *Base = IvarRef->getBase();
537 if (const auto *ICE = dyn_cast<ImplicitCastExpr>(Base))
538 Base = ICE->getSubExpr();
539
540 if (const auto *DRE = dyn_cast<DeclRefExpr>(Base))
541 if (const auto *ID = dyn_cast<ImplicitParamDecl>(DRE->getDecl()))
542 if (ID->getParameterKind() == ImplicitParamKind::ObjCSelf)
543 return true;
544
545 return false;
546 }
547 return false;
548}
549
550/// Attempts to find the region of interest in a given CXX decl,
551/// by either following the base classes or fields.
552/// Dereferences fields up to a given recursion limit.
553/// Note that \p Vec is passed by value, leading to quadratic copying cost,
554/// but it's OK in practice since its length is limited to DEREFERENCE_LIMIT.
555/// \return A chain fields leading to the region of interest or std::nullopt.
556const std::optional<NoStoreFuncVisitor::RegionVector>
557NoStoreFuncVisitor::findRegionOfInterestInRecord(
558 const RecordDecl *RD, ProgramStateRef State, const MemRegion *R,
559 const NoStoreFuncVisitor::RegionVector &Vec /* = {} */,
560 int depth /* = 0 */) {
561
562 if (depth == DEREFERENCE_LIMIT) // Limit the recursion depth.
563 return std::nullopt;
564
565 if (const auto *RDX = dyn_cast<CXXRecordDecl>(RD))
566 if (!RDX->hasDefinition())
567 return std::nullopt;
568
569 // Recursively examine the base classes.
570 // Note that following base classes does not increase the recursion depth.
571 if (const auto *RDX = dyn_cast<CXXRecordDecl>(RD))
572 for (const auto &II : RDX->bases())
573 if (const RecordDecl *RRD = II.getType()->getAsRecordDecl())
574 if (std::optional<RegionVector> Out =
575 findRegionOfInterestInRecord(RRD, State, R, Vec, depth))
576 return Out;
577
578 for (const FieldDecl *I : RD->fields()) {
579 QualType FT = I->getType();
580 const FieldRegion *FR = MmrMgr.getFieldRegion(I, cast<SubRegion>(R));
581 const SVal V = State->getSVal(FR);
582 const MemRegion *VR = V.getAsRegion();
583
584 RegionVector VecF = Vec;
585 VecF.push_back(FR);
586
587 if (RegionOfInterest == VR)
588 return VecF;
589
590 if (const RecordDecl *RRD = FT->getAsRecordDecl())
591 if (auto Out =
592 findRegionOfInterestInRecord(RRD, State, FR, VecF, depth + 1))
593 return Out;
594
595 QualType PT = FT->getPointeeType();
596 if (PT.isNull() || PT->isVoidType() || !VR)
597 continue;
598
599 if (const RecordDecl *RRD = PT->getAsRecordDecl())
600 if (std::optional<RegionVector> Out =
601 findRegionOfInterestInRecord(RRD, State, VR, VecF, depth + 1))
602 return Out;
603 }
604
605 return std::nullopt;
606}
607
609NoStoreFuncVisitor::maybeEmitNoteForObjCSelf(PathSensitiveBugReport &R,
610 const ObjCMethodCall &Call,
611 const ExplodedNode *N) {
612 if (const auto *IvarR = dyn_cast<ObjCIvarRegion>(RegionOfInterest)) {
613 const MemRegion *SelfRegion = Call.getReceiverSVal().getAsRegion();
614 if (RegionOfInterest->isSubRegionOf(SelfRegion) &&
615 potentiallyWritesIntoIvar(Call.getRuntimeDefinition().getDecl(),
616 IvarR->getDecl()))
617 return maybeEmitNote(R, Call, N, {}, SelfRegion, "self",
618 /*FirstIsReferenceType=*/false, 1);
619 }
620 return nullptr;
621}
622
624NoStoreFuncVisitor::maybeEmitNoteForCXXThis(PathSensitiveBugReport &R,
626 const ExplodedNode *N) {
627 const MemRegion *ThisR = Call.getCXXThisVal().getAsRegion();
628 if (RegionOfInterest->isSubRegionOf(ThisR) && !Call.getDecl()->isImplicit())
629 return maybeEmitNote(R, Call, N, {}, ThisR, "this",
630 /*FirstIsReferenceType=*/false, 1);
631
632 // Do not generate diagnostics for not modified parameters in
633 // constructors.
634 return nullptr;
635}
636
637/// \return whether \p Ty points to a const type, or is a const reference.
638static bool isPointerToConst(QualType Ty) {
639 return !Ty->getPointeeType().isNull() &&
641}
642
643PathDiagnosticPieceRef NoStoreFuncVisitor::maybeEmitNoteForParameters(
644 PathSensitiveBugReport &R, const CallEvent &Call, const ExplodedNode *N) {
645 ArrayRef<ParmVarDecl *> Parameters = Call.parameters();
646 for (unsigned I = 0; I < Call.getNumArgs() && I < Parameters.size(); ++I) {
647 const ParmVarDecl *PVD = Parameters[I];
648 SVal V = Call.getArgSVal(I);
649 bool ParamIsReferenceType = PVD->getType()->isReferenceType();
650 std::string ParamName = PVD->getNameAsString();
651
652 unsigned IndirectionLevel = 1;
653 QualType T = PVD->getType();
654 while (const MemRegion *MR = V.getAsRegion()) {
655 if (RegionOfInterest->isSubRegionOf(MR) && !isPointerToConst(T))
656 return maybeEmitNote(R, Call, N, {}, MR, ParamName,
657 ParamIsReferenceType, IndirectionLevel);
658
659 QualType PT = T->getPointeeType();
660 if (PT.isNull() || PT->isVoidType())
661 break;
662
663 ProgramStateRef State = N->getState();
664
665 if (const RecordDecl *RD = PT->getAsRecordDecl())
666 if (std::optional<RegionVector> P =
667 findRegionOfInterestInRecord(RD, State, MR))
668 return maybeEmitNote(R, Call, N, *P, RegionOfInterest, ParamName,
669 ParamIsReferenceType, IndirectionLevel);
670
671 V = State->getSVal(MR, PT);
672 T = PT;
673 IndirectionLevel++;
674 }
675 }
676
677 return nullptr;
678}
679
680bool NoStoreFuncVisitor::wasModifiedBeforeCallExit(
681 const ExplodedNode *CurrN, const ExplodedNode *CallExitBeginN) {
682 return ::wasRegionOfInterestModifiedAt(
683 RegionOfInterest, CurrN,
684 CallExitBeginN->getState()->getSVal(RegionOfInterest));
685}
686
687static llvm::StringLiteral WillBeUsedForACondition =
688 ", which participates in a condition later";
689
690PathDiagnosticPieceRef NoStoreFuncVisitor::maybeEmitNote(
692 const RegionVector &FieldChain, const MemRegion *MatchedRegion,
693 StringRef FirstElement, bool FirstIsReferenceType,
694 unsigned IndirectionLevel) {
695
698
699 // For now this shouldn't trigger, but once it does (as we add more
700 // functions to the body farm), we'll need to decide if these reports
701 // are worth suppressing as well.
702 if (!L.hasValidLocation())
703 return nullptr;
704
705 SmallString<256> sbuf;
706 llvm::raw_svector_ostream os(sbuf);
707 os << "Returning without writing to '";
708
709 // Do not generate the note if failed to pretty-print.
710 if (!prettyPrintRegionName(FieldChain, MatchedRegion, FirstElement,
711 FirstIsReferenceType, IndirectionLevel, os))
712 return nullptr;
713
714 os << "'";
717 return std::make_shared<PathDiagnosticEventPiece>(L, os.str());
718}
719
720bool NoStoreFuncVisitor::prettyPrintRegionName(const RegionVector &FieldChain,
721 const MemRegion *MatchedRegion,
722 StringRef FirstElement,
723 bool FirstIsReferenceType,
724 unsigned IndirectionLevel,
725 llvm::raw_svector_ostream &os) {
726
727 if (FirstIsReferenceType)
728 IndirectionLevel--;
729
730 RegionVector RegionSequence;
731
732 // Add the regions in the reverse order, then reverse the resulting array.
733 assert(RegionOfInterest->isSubRegionOf(MatchedRegion));
734 const MemRegion *R = RegionOfInterest;
735 while (R != MatchedRegion) {
736 RegionSequence.push_back(R);
737 R = cast<SubRegion>(R)->getSuperRegion();
738 }
739 std::reverse(RegionSequence.begin(), RegionSequence.end());
740 RegionSequence.append(FieldChain.begin(), FieldChain.end());
741
742 StringRef Sep;
743 for (const MemRegion *R : RegionSequence) {
744
745 // Just keep going up to the base region.
746 // Element regions may appear due to casts.
748 continue;
749
750 if (Sep.empty())
751 Sep = prettyPrintFirstElement(FirstElement,
752 /*MoreItemsExpected=*/true,
753 IndirectionLevel, os);
754
755 os << Sep;
756
757 // Can only reasonably pretty-print DeclRegions.
758 if (!isa<DeclRegion>(R))
759 return false;
760
761 const auto *DR = cast<DeclRegion>(R);
762 Sep = DR->getValueType()->isAnyPointerType() ? "->" : ".";
763 DR->getDecl()->getDeclName().print(os, PP);
764 }
765
766 if (Sep.empty())
767 prettyPrintFirstElement(FirstElement,
768 /*MoreItemsExpected=*/false, IndirectionLevel, os);
769 return true;
770}
771
772StringRef NoStoreFuncVisitor::prettyPrintFirstElement(
773 StringRef FirstElement, bool MoreItemsExpected, int IndirectionLevel,
774 llvm::raw_svector_ostream &os) {
775 StringRef Out = ".";
776
777 if (IndirectionLevel > 0 && MoreItemsExpected) {
778 IndirectionLevel--;
779 Out = "->";
780 }
781
782 if (IndirectionLevel > 0 && MoreItemsExpected)
783 os << "(";
784
785 for (int i = 0; i < IndirectionLevel; i++)
786 os << "*";
787 os << FirstElement;
788
789 if (IndirectionLevel > 0 && MoreItemsExpected)
790 os << ")";
791
792 return Out;
793}
794
795//===----------------------------------------------------------------------===//
796// Implementation of MacroNullReturnSuppressionVisitor.
797//===----------------------------------------------------------------------===//
798
799namespace {
800
801/// Suppress null-pointer-dereference bugs where dereferenced null was returned
802/// the macro.
803class MacroNullReturnSuppressionVisitor final : public BugReporterVisitor {
804 const SubRegion *RegionOfInterest;
805 const SVal ValueAtDereference;
806
807 // Do not invalidate the reports where the value was modified
808 // after it got assigned to from the macro.
809 bool WasModified = false;
810
811public:
812 MacroNullReturnSuppressionVisitor(const SubRegion *R, const SVal V)
813 : RegionOfInterest(R), ValueAtDereference(V) {}
814
815 PathDiagnosticPieceRef VisitNode(const ExplodedNode *N,
816 BugReporterContext &BRC,
817 PathSensitiveBugReport &BR) override {
818 if (WasModified)
819 return nullptr;
820
821 auto BugPoint = BR.getErrorNode()->getLocation().getAs<StmtPoint>();
822 if (!BugPoint)
823 return nullptr;
824
825 const SourceManager &SMgr = BRC.getSourceManager();
826 if (auto Loc = matchAssignment(N)) {
827 if (isFunctionMacroExpansion(*Loc, SMgr)) {
828 std::string MacroName = std::string(getMacroName(*Loc, BRC));
829 SourceLocation BugLoc = BugPoint->getStmt()->getBeginLoc();
830 if (!BugLoc.isMacroID() || getMacroName(BugLoc, BRC) != MacroName)
831 BR.markInvalid(getTag(), MacroName.c_str());
832 }
833 }
834
835 if (wasRegionOfInterestModifiedAt(RegionOfInterest, N, ValueAtDereference))
836 WasModified = true;
837
838 return nullptr;
839 }
840
841 static void addMacroVisitorIfNecessary(
842 const ExplodedNode *N, const MemRegion *R,
843 bool EnableNullFPSuppression, PathSensitiveBugReport &BR,
844 const SVal V) {
845 AnalyzerOptions &Options = N->getState()->getAnalysisManager().options;
846 if (EnableNullFPSuppression && Options.ShouldSuppressNullReturnPaths &&
847 isa<Loc>(V))
848 BR.addVisitor<MacroNullReturnSuppressionVisitor>(R->getAs<SubRegion>(),
849 V);
850 }
851
852 void* getTag() const {
853 static int Tag = 0;
854 return static_cast<void *>(&Tag);
855 }
856
857 void Profile(llvm::FoldingSetNodeID &ID) const override {
858 ID.AddPointer(getTag());
859 }
860
861private:
862 /// \return Source location of right hand side of an assignment
863 /// into \c RegionOfInterest, empty optional if none found.
864 std::optional<SourceLocation> matchAssignment(const ExplodedNode *N) {
865 const Stmt *S = N->getStmtForDiagnostics();
866 ProgramStateRef State = N->getState();
867 if (!S)
868 return std::nullopt;
869
870 if (const auto *DS = dyn_cast<DeclStmt>(S)) {
871 if (const auto *VD = dyn_cast<VarDecl>(DS->getSingleDecl()))
872 if (const Expr *RHS = VD->getInit())
873 if (RegionOfInterest->isSubRegionOf(
874 State->getLValue(VD, N->getStackFrame()).getAsRegion()))
875 return RHS->getBeginLoc();
876 } else if (const auto *BO = dyn_cast<BinaryOperator>(S)) {
877 const MemRegion *R = N->getSVal(BO->getLHS()).getAsRegion();
878 const Expr *RHS = BO->getRHS();
879 if (BO->isAssignmentOp() && RegionOfInterest->isSubRegionOf(R)) {
880 return RHS->getBeginLoc();
881 }
882 }
883 return std::nullopt;
884 }
885};
886
887} // end of anonymous namespace
888
889namespace {
890
891/// Emits an extra note at the return statement of an interesting stack frame.
892///
893/// The returned value is marked as an interesting value, and if it's null,
894/// adds a visitor to track where it became null.
895///
896/// This visitor is intended to be used when another visitor discovers that an
897/// interesting value comes from an inlined function call.
898class ReturnVisitor : public TrackingBugReporterVisitor {
899 const StackFrame *CalleeSF;
900 enum {
901 Initial,
902 MaybeUnsuppress,
903 Satisfied
904 } Mode = Initial;
905
906 bool EnableNullFPSuppression;
907 bool ShouldInvalidate = true;
908 AnalyzerOptions& Options;
910
911public:
912 ReturnVisitor(TrackerRef ParentTracker, const StackFrame *Frame,
913 bool Suppressed, AnalyzerOptions &Options,
915 : TrackingBugReporterVisitor(ParentTracker), CalleeSF(Frame),
916 EnableNullFPSuppression(Suppressed), Options(Options), TKind(TKind) {}
917
918 static void *getTag() {
919 static int Tag = 0;
920 return static_cast<void *>(&Tag);
921 }
922
923 void Profile(llvm::FoldingSetNodeID &ID) const override {
924 ID.AddPointer(ReturnVisitor::getTag());
925 ID.AddPointer(CalleeSF);
926 ID.AddBoolean(EnableNullFPSuppression);
927 }
928
929 PathDiagnosticPieceRef visitNodeInitial(const ExplodedNode *N,
930 BugReporterContext &BRC,
931 PathSensitiveBugReport &BR) {
932 // Only print a message at the interesting return statement.
933 if (N->getStackFrame() != CalleeSF)
934 return nullptr;
935
936 std::optional<StmtPoint> SP = N->getLocationAs<StmtPoint>();
937 if (!SP)
938 return nullptr;
939
940 const auto *Ret = dyn_cast<ReturnStmt>(SP->getStmt());
941 if (!Ret)
942 return nullptr;
943
944 // Okay, we're at the right return statement, but do we have the return
945 // value available?
946 ProgramStateRef State = N->getState();
947 const Expr *RV = Ret->getRetValue();
948 if (!RV)
949 return nullptr;
950 SVal V = State->getSVal(RV, CalleeSF);
951 if (V.isUnknownOrUndef())
952 return nullptr;
953
954 // Don't print any more notes after this one.
955 Mode = Satisfied;
956
957 const Expr *RetE = Ret->getRetValue();
958 assert(RetE && "Tracking a return value for a void function");
959
960 // Handle cases where a reference is returned and then immediately used.
961 std::optional<Loc> LValue;
962 if (RetE->isGLValue()) {
963 if ((LValue = V.getAs<Loc>())) {
964 SVal RValue = State->getRawSVal(*LValue, RetE->getType());
965 if (isa<DefinedSVal>(RValue))
966 V = RValue;
967 }
968 }
969
970 // Ignore aggregate rvalues.
972 return nullptr;
973
974 RetE = RetE->IgnoreParenCasts();
975
976 // Let's track the return value.
977 getParentTracker().track(RetE, N, {TKind, EnableNullFPSuppression});
978
979 // Build an appropriate message based on the return value.
980 SmallString<64> Msg;
981 llvm::raw_svector_ostream Out(Msg);
982
983 bool WouldEventBeMeaningless = false;
984
985 if (State->isNull(V).isConstrainedTrue()) {
986 if (isa<Loc>(V)) {
987
988 // If we have counter-suppression enabled, make sure we keep visiting
989 // future nodes. We want to emit a path note as well, in case
990 // the report is resurrected as valid later on.
991 if (EnableNullFPSuppression &&
992 Options.ShouldAvoidSuppressingNullArgumentPaths)
993 Mode = MaybeUnsuppress;
994
995 if (RetE->getType()->isObjCObjectPointerType()) {
996 Out << "Returning nil";
997 } else {
998 Out << "Returning null pointer";
999 }
1000 } else {
1001 Out << "Returning zero";
1002 }
1003
1004 } else {
1005 if (auto CI = V.getAs<nonloc::ConcreteInt>()) {
1006 Out << "Returning the value " << CI->getValue();
1007 } else {
1008 // There is nothing interesting about returning a value, when it is
1009 // plain value without any constraints, and the function is guaranteed
1010 // to return that every time. We could use CFG::isLinear() here, but
1011 // constexpr branches are obvious to the compiler, not necesserily to
1012 // the programmer.
1013 if (N->getCFG().size() == 3)
1014 WouldEventBeMeaningless = true;
1015
1016 Out << (isa<Loc>(V) ? "Returning pointer" : "Returning value");
1017 }
1018 }
1019
1020 if (LValue) {
1021 if (const MemRegion *MR = LValue->getAsRegion()) {
1022 if (MR->canPrintPretty()) {
1023 Out << " (reference to ";
1024 MR->printPretty(Out);
1025 Out << ")";
1026 }
1027 }
1028 } else {
1029 // FIXME: We should have a more generalized location printing mechanism.
1030 if (const auto *DR = dyn_cast<DeclRefExpr>(RetE))
1031 if (const auto *DD = dyn_cast<DeclaratorDecl>(DR->getDecl()))
1032 Out << " (loaded from '" << *DD << "')";
1033 }
1034
1035 PathDiagnosticLocation L(Ret, BRC.getSourceManager(), CalleeSF);
1036 if (!L.isValid() || !L.asLocation().isValid())
1037 return nullptr;
1038
1039 if (TKind == bugreporter::TrackingKind::Condition)
1041
1042 auto EventPiece = std::make_shared<PathDiagnosticEventPiece>(L, Out.str());
1043
1044 // If we determined that the note is meaningless, make it prunable, and
1045 // don't mark the stackframe interesting.
1046 if (WouldEventBeMeaningless)
1047 EventPiece->setPrunable(true);
1048 else
1049 BR.markInteresting(CalleeSF);
1050
1051 return EventPiece;
1052 }
1053
1054 PathDiagnosticPieceRef visitNodeMaybeUnsuppress(const ExplodedNode *N,
1055 BugReporterContext &BRC,
1056 PathSensitiveBugReport &BR) {
1057 assert(Options.ShouldAvoidSuppressingNullArgumentPaths);
1058
1059 // Are we at the entry node for this call?
1060 std::optional<CallEnter> CE = N->getLocationAs<CallEnter>();
1061 if (!CE)
1062 return nullptr;
1063
1064 if (CE->getCalleeStackFrame() != CalleeSF)
1065 return nullptr;
1066
1067 Mode = Satisfied;
1068
1069 // Don't automatically suppress a report if one of the arguments is
1070 // known to be a null pointer. Instead, start tracking /that/ null
1071 // value back to its origin.
1072 ProgramStateManager &StateMgr = BRC.getStateManager();
1073 CallEventManager &CallMgr = StateMgr.getCallEventManager();
1074
1075 ProgramStateRef State = N->getState();
1076 CallEventRef<> Call = CallMgr.getCaller(CalleeSF, State);
1077 for (unsigned I = 0, E = Call->getNumArgs(); I != E; ++I) {
1078 std::optional<Loc> ArgV = Call->getArgSVal(I).getAs<Loc>();
1079 if (!ArgV)
1080 continue;
1081
1082 const Expr *ArgE = Call->getArgExpr(I);
1083 if (!ArgE)
1084 continue;
1085
1086 // Is it possible for this argument to be non-null?
1087 if (!State->isNull(*ArgV).isConstrainedTrue())
1088 continue;
1089
1090 if (getParentTracker()
1091 .track(ArgE, N, {TKind, EnableNullFPSuppression})
1092 .FoundSomethingToTrack)
1093 ShouldInvalidate = false;
1094
1095 // If we /can't/ track the null pointer, we should err on the side of
1096 // false negatives, and continue towards marking this report invalid.
1097 // (We will still look at the other arguments, though.)
1098 }
1099
1100 return nullptr;
1101 }
1102
1103 PathDiagnosticPieceRef VisitNode(const ExplodedNode *N,
1104 BugReporterContext &BRC,
1105 PathSensitiveBugReport &BR) override {
1106 switch (Mode) {
1107 case Initial:
1108 return visitNodeInitial(N, BRC, BR);
1109 case MaybeUnsuppress:
1110 return visitNodeMaybeUnsuppress(N, BRC, BR);
1111 case Satisfied:
1112 return nullptr;
1113 }
1114
1115 llvm_unreachable("Invalid visit mode!");
1116 }
1117
1118 void finalizeVisitor(BugReporterContext &, const ExplodedNode *,
1119 PathSensitiveBugReport &BR) override {
1120 if (EnableNullFPSuppression && ShouldInvalidate)
1121 BR.markInvalid(ReturnVisitor::getTag(), CalleeSF);
1122 }
1123};
1124
1125//===----------------------------------------------------------------------===//
1126// StoreSiteFinder
1127//===----------------------------------------------------------------------===//
1128
1129/// Finds last store into the given region,
1130/// which is different from a given symbolic value.
1131class StoreSiteFinder final : public TrackingBugReporterVisitor {
1132 const MemRegion *R;
1133 SVal V;
1134 bool Satisfied = false;
1135
1136 TrackingOptions Options;
1137 const StackFrame *OriginSF;
1138
1139public:
1140 /// \param V We're searching for the store where \c R received this value.
1141 /// \param R The region we're tracking.
1142 /// \param Options Tracking behavior options.
1143 /// \param OriginSF Only adds notes when the last store happened in a
1144 /// different stackframe to this one. Disregarded if the tracking kind
1145 /// is thorough.
1146 /// This is useful, because for non-tracked regions, notes about
1147 /// changes to its value in a nested stackframe could be pruned, and
1148 /// this visitor can prevent that without polluting the bugpath too
1149 /// much.
1150 StoreSiteFinder(bugreporter::TrackerRef ParentTracker, SVal V,
1151 const MemRegion *R, TrackingOptions Options,
1152 const StackFrame *OriginSF = nullptr)
1153 : TrackingBugReporterVisitor(ParentTracker), R(R), V(V), Options(Options),
1154 OriginSF(OriginSF) {
1155 assert(R);
1156 }
1157
1158 void Profile(llvm::FoldingSetNodeID &ID) const override;
1159
1160 PathDiagnosticPieceRef VisitNode(const ExplodedNode *N,
1161 BugReporterContext &BRC,
1162 PathSensitiveBugReport &BR) override;
1163};
1164} // namespace
1165
1166void StoreSiteFinder::Profile(llvm::FoldingSetNodeID &ID) const {
1167 static int tag = 0;
1168 ID.AddPointer(&tag);
1169 ID.AddPointer(R);
1170 ID.Add(V);
1171 ID.AddInteger(static_cast<int>(Options.Kind));
1172 ID.AddBoolean(Options.EnableNullFPSuppression);
1173}
1174
1175/// Returns true if \p N represents the DeclStmt declaring and initializing
1176/// \p VR.
1177static bool isInitializationOfVar(const ExplodedNode *N, const VarRegion *VR) {
1178 std::optional<PostStmt> P = N->getLocationAs<PostStmt>();
1179 if (!P)
1180 return false;
1181
1182 const DeclStmt *DS = P->getStmtAs<DeclStmt>();
1183 if (!DS)
1184 return false;
1185
1186 if (DS->getSingleDecl() != VR->getDecl())
1187 return false;
1188
1189 const auto *FrameSpace =
1191
1192 if (!FrameSpace) {
1193 // If we ever directly evaluate global DeclStmts, this assertion will be
1194 // invalid, but this still seems preferable to silently accepting an
1195 // initialization that may be for a path-sensitive variable.
1196 [[maybe_unused]] bool IsLocalStaticOrLocalExtern =
1197 VR->getDecl()->isStaticLocal() || VR->getDecl()->isLocalExternDecl();
1198 assert(IsLocalStaticOrLocalExtern &&
1199 "Declared a variable on the stack without Stack memspace?");
1200 return true;
1201 }
1202
1203 assert(VR->getDecl()->hasLocalStorage());
1204 return FrameSpace->getStackFrame() == N->getStackFrame();
1205}
1206
1207static bool isObjCPointer(const MemRegion *R) {
1208 if (R->isBoundable())
1209 if (const auto *TR = dyn_cast<TypedValueRegion>(R))
1210 return TR->getValueType()->isObjCObjectPointerType();
1211
1212 return false;
1213}
1214
1215static bool isObjCPointer(const ValueDecl *D) {
1216 return D->getType()->isObjCObjectPointerType();
1217}
1218
1219namespace {
1220using DestTypeValue = std::pair<const StoreInfo &, loc::ConcreteInt>;
1221
1222llvm::raw_ostream &operator<<(llvm::raw_ostream &OS, const DestTypeValue &Val) {
1223 if (auto *TyR = Val.first.Dest->getAs<TypedRegion>()) {
1224 QualType LocTy = TyR->getLocationType();
1225 if (!LocTy.isNull()) {
1226 if (auto *PtrTy = LocTy->getAs<PointerType>()) {
1227 std::string PStr = PtrTy->getPointeeType().getAsString();
1228 if (!PStr.empty())
1229 OS << "(" << PStr << ")";
1230 }
1231 }
1232 }
1233 SmallString<16> ValStr;
1234 Val.second.getValue()->toString(ValStr, 10, true);
1235 OS << ValStr;
1236 return OS;
1237}
1238} // namespace
1239
1240/// Show diagnostics for initializing or declaring a region \p R with a bad value.
1241static void showBRDiagnostics(llvm::raw_svector_ostream &OS, StoreInfo SI) {
1242 const bool HasPrefix = SI.Dest->canPrintPretty();
1243
1244 if (HasPrefix) {
1245 SI.Dest->printPretty(OS);
1246 OS << " ";
1247 }
1248
1249 const char *Action = nullptr;
1250
1251 switch (SI.StoreKind) {
1253 Action = HasPrefix ? "initialized to " : "Initializing to ";
1254 break;
1256 Action = HasPrefix ? "captured by block as " : "Captured by block as ";
1257 break;
1258 default:
1259 llvm_unreachable("Unexpected store kind");
1260 }
1261
1262 if (auto CVal = SI.Value.getAs<loc::ConcreteInt>()) {
1263 if (!*CVal->getValue())
1264 OS << Action << (isObjCPointer(SI.Dest) ? "nil" : "a null pointer value");
1265 else
1266 OS << Action << DestTypeValue(SI, *CVal);
1267
1268 } else if (auto CVal = SI.Value.getAs<nonloc::ConcreteInt>()) {
1269 OS << Action << CVal->getValue();
1270
1271 } else if (SI.Origin && SI.Origin->canPrintPretty()) {
1272 OS << Action << "the value of ";
1273 SI.Origin->printPretty(OS);
1274
1275 } else if (SI.StoreKind == StoreInfo::Initialization) {
1276 if (const auto *VR = dyn_cast<VarRegion>(SI.Dest)) {
1277 const VarDecl *VD = VR->getDecl();
1278 if (!VD->getInit() && !VD->hasGlobalStorage()) {
1279 OS << (HasPrefix ? "declared" : "Declared")
1280 << " without an initial value";
1281 return;
1282 }
1283 }
1284 OS << (HasPrefix ? "initialized" : "Initialized") << " here";
1285 }
1286}
1287
1288/// Display diagnostics for passing bad region as a parameter.
1289static void showBRParamDiagnostics(llvm::raw_svector_ostream &OS,
1290 StoreInfo SI) {
1291 const auto *VR = cast<VarRegion>(SI.Dest);
1292 const auto *D = VR->getDecl();
1293
1294 OS << "Passing ";
1295
1296 if (auto CI = SI.Value.getAs<loc::ConcreteInt>()) {
1297 if (!*CI->getValue())
1298 OS << (isObjCPointer(D) ? "nil object reference" : "null pointer value");
1299 else
1300 OS << (isObjCPointer(D) ? "object reference of value " : "pointer value ")
1301 << DestTypeValue(SI, *CI);
1302
1303 } else if (SI.Value.isUndef()) {
1304 OS << "uninitialized value";
1305
1306 } else if (auto CI = SI.Value.getAs<nonloc::ConcreteInt>()) {
1307 OS << "the value " << CI->getValue();
1308
1309 } else if (SI.Origin && SI.Origin->canPrintPretty()) {
1310 SI.Origin->printPretty(OS);
1311
1312 } else {
1313 OS << "value";
1314 }
1315
1316 if (const auto *Param = dyn_cast<ParmVarDecl>(VR->getDecl())) {
1317 // Printed parameter indexes are 1-based, not 0-based.
1318 unsigned Idx = Param->getFunctionScopeIndex() + 1;
1319 OS << " via " << Idx << llvm::getOrdinalSuffix(Idx) << " parameter";
1320 if (VR->canPrintPretty()) {
1321 OS << " ";
1322 VR->printPretty(OS);
1323 }
1324 } else if (const auto *ImplParam = dyn_cast<ImplicitParamDecl>(D)) {
1325 if (ImplParam->getParameterKind() == ImplicitParamKind::ObjCSelf) {
1326 OS << " via implicit parameter 'self'";
1327 }
1328 }
1329}
1330
1331/// Show default diagnostics for storing bad region.
1332static void showBRDefaultDiagnostics(llvm::raw_svector_ostream &OS,
1333 StoreInfo SI) {
1334 const bool HasSuffix = SI.Dest->canPrintPretty();
1335
1336 if (auto CV = SI.Value.getAs<loc::ConcreteInt>()) {
1337 APSIntPtr V = CV->getValue();
1338 if (!*V)
1339 OS << (isObjCPointer(SI.Dest)
1340 ? "nil object reference stored"
1341 : (HasSuffix ? "Null pointer value stored"
1342 : "Storing null pointer value"));
1343 else {
1344 if (isObjCPointer(SI.Dest)) {
1345 OS << "object reference of value " << DestTypeValue(SI, *CV)
1346 << " stored";
1347 } else {
1348 if (HasSuffix)
1349 OS << "Pointer value of " << DestTypeValue(SI, *CV) << " stored";
1350 else
1351 OS << "Storing pointer value of " << DestTypeValue(SI, *CV);
1352 }
1353 }
1354 } else if (SI.Value.isUndef()) {
1355 OS << (HasSuffix ? "Uninitialized value stored"
1356 : "Storing uninitialized value");
1357
1358 } else if (auto CV = SI.Value.getAs<nonloc::ConcreteInt>()) {
1359 if (HasSuffix)
1360 OS << "The value " << CV->getValue() << " is assigned";
1361 else
1362 OS << "Assigning " << CV->getValue();
1363
1364 } else if (SI.Origin && SI.Origin->canPrintPretty()) {
1365 if (HasSuffix) {
1366 OS << "The value of ";
1367 SI.Origin->printPretty(OS);
1368 OS << " is assigned";
1369 } else {
1370 OS << "Assigning the value of ";
1371 SI.Origin->printPretty(OS);
1372 }
1373
1374 } else {
1375 OS << (HasSuffix ? "Value assigned" : "Assigning value");
1376 }
1377
1378 if (HasSuffix) {
1379 OS << " to ";
1380 SI.Dest->printPretty(OS);
1381 }
1382}
1383
1385 if (!CE)
1386 return false;
1387
1388 const auto *CtorDecl = CE->getConstructor();
1389
1390 return CtorDecl->isCopyOrMoveConstructor() && CtorDecl->isTrivial();
1391}
1392
1394 const MemRegion *R) {
1395
1396 const auto *TVR = dyn_cast_or_null<TypedValueRegion>(R);
1397
1398 if (!TVR)
1399 return nullptr;
1400
1401 const auto ITy = ILE->getType().getCanonicalType();
1402
1403 // Push each sub-region onto the stack.
1404 std::stack<const TypedValueRegion *> TVRStack;
1405 while (isa<FieldRegion>(TVR) || isa<ElementRegion>(TVR)) {
1406 // We found a region that matches the type of the init list,
1407 // so we assume this is the outer-most region. This can happen
1408 // if the initializer list is inside a class. If our assumption
1409 // is wrong, we return a nullptr in the end.
1410 if (ITy == TVR->getValueType().getCanonicalType())
1411 break;
1412
1413 TVRStack.push(TVR);
1414 TVR = cast<TypedValueRegion>(TVR->getSuperRegion());
1415 }
1416
1417 // If the type of the outer most region doesn't match the type
1418 // of the ILE, we can't match the ILE and the region.
1419 if (ITy != TVR->getValueType().getCanonicalType())
1420 return nullptr;
1421
1422 const Expr *Init = ILE;
1423 while (!TVRStack.empty()) {
1424 TVR = TVRStack.top();
1425 TVRStack.pop();
1426
1427 // We hit something that's not an init list before
1428 // running out of regions, so we most likely failed.
1429 if (!isa<InitListExpr>(Init))
1430 return nullptr;
1431
1432 ILE = cast<InitListExpr>(Init);
1433 auto NumInits = ILE->getNumInits();
1434
1435 if (const auto *FR = dyn_cast<FieldRegion>(TVR)) {
1436 const auto *FD = FR->getDecl();
1437
1438 if (FD->getFieldIndex() >= NumInits)
1439 return nullptr;
1440
1441 Init = ILE->getInit(FD->getFieldIndex());
1442 } else if (const auto *ER = dyn_cast<ElementRegion>(TVR)) {
1443 const auto Ind = ER->getIndex();
1444
1445 // If index is symbolic, we can't figure out which expression
1446 // belongs to the region.
1447 if (!Ind.isConstant())
1448 return nullptr;
1449
1450 const auto IndVal = Ind.getAsInteger()->getLimitedValue();
1451 if (IndVal >= NumInits)
1452 return nullptr;
1453
1454 Init = ILE->getInit(IndVal);
1455 }
1456 }
1457
1458 return Init;
1459}
1460
1461PathDiagnosticPieceRef StoreSiteFinder::VisitNode(const ExplodedNode *Succ,
1462 BugReporterContext &BRC,
1464 if (Satisfied)
1465 return nullptr;
1466
1467 const ExplodedNode *StoreSite = nullptr;
1468 const ExplodedNode *Pred = Succ->getFirstPred();
1469 const Expr *InitE = nullptr;
1470 bool IsParam = false;
1471
1472 // First see if we reached the declaration of the region.
1473 if (const auto *VR = dyn_cast<VarRegion>(R)) {
1474 if (isInitializationOfVar(Pred, VR)) {
1475 StoreSite = Pred;
1476 InitE = VR->getDecl()->getInit();
1477 }
1478 }
1479
1480 // If this is a post initializer expression, initializing the region, we
1481 // should track the initializer expression.
1482 if (std::optional<PostInitializer> PIP =
1483 Pred->getLocationAs<PostInitializer>()) {
1484 const MemRegion *FieldReg = (const MemRegion *)PIP->getLocationValue();
1485 if (FieldReg == R) {
1486 StoreSite = Pred;
1487 InitE = PIP->getInitializer()->getInit();
1488 }
1489 }
1490
1491 // Otherwise, see if this is the store site:
1492 // (1) Succ has this binding and Pred does not, i.e. this is
1493 // where the binding first occurred.
1494 // (2) Succ has this binding and is a PostStore node for this region, i.e.
1495 // the same binding was re-assigned here.
1496 if (!StoreSite) {
1497 if (Succ->getState()->getSVal(R) != V)
1498 return nullptr;
1499
1500 if (hasVisibleUpdate(Pred, Pred->getState()->getSVal(R), Succ, V)) {
1501 std::optional<PostStore> PS = Succ->getLocationAs<PostStore>();
1502 if (!PS || PS->getLocationValue() != R)
1503 return nullptr;
1504 }
1505
1506 StoreSite = Succ;
1507
1508 if (std::optional<PostStmt> P = Succ->getLocationAs<PostStmt>()) {
1509 // If this is an assignment expression, we can track the value
1510 // being assigned.
1511 if (const BinaryOperator *BO = P->getStmtAs<BinaryOperator>()) {
1512 if (BO->isAssignmentOp())
1513 InitE = BO->getRHS();
1514 }
1515 // If we have a declaration like 'S s{1,2}' that needs special
1516 // handling, we handle it here.
1517 else if (const auto *DS = P->getStmtAs<DeclStmt>()) {
1518 const auto *Decl = DS->getSingleDecl();
1519 if (isa<VarDecl>(Decl)) {
1520 const auto *VD = cast<VarDecl>(Decl);
1521
1522 // FIXME: Here we only track the inner most region, so we lose
1523 // information, but it's still better than a crash or no information
1524 // at all.
1525 //
1526 // E.g.: The region we have is 's.s2.s3.s4.y' and we only track 'y',
1527 // and throw away the rest.
1528 if (const auto *ILE = dyn_cast<InitListExpr>(VD->getInit()))
1529 InitE = tryExtractInitializerFromList(ILE, R);
1530 }
1531 } else if (const auto *CE = P->getStmtAs<CXXConstructExpr>()) {
1532
1533 const auto State = Succ->getState();
1534
1536 // Migrate the field regions from the current object to
1537 // the parent object. If we track 'a.y.e' and encounter
1538 // 'S a = b' then we need to track 'b.y.e'.
1539
1540 // Push the regions to a stack, from last to first, so
1541 // considering the example above the stack will look like
1542 // (bottom) 'e' -> 'y' (top).
1543
1544 std::stack<const SubRegion *> SRStack;
1545 const SubRegion *SR = cast<SubRegion>(R);
1546 while (isa<FieldRegion>(SR) || isa<ElementRegion>(SR)) {
1547 SRStack.push(SR);
1548 SR = cast<SubRegion>(SR->getSuperRegion());
1549 }
1550
1551 // Get the region for the object we copied/moved from.
1552 const auto *OriginEx = CE->getArg(0);
1553 const auto OriginVal =
1554 State->getSVal(OriginEx, Succ->getStackFrame());
1555
1556 // Pop the stored field regions and apply them to the origin
1557 // object in the same order we had them on the copy.
1558 // OriginField will evolve like 'b' -> 'b.y' -> 'b.y.e'.
1559 SVal OriginField = OriginVal;
1560 while (!SRStack.empty()) {
1561 const auto *TopR = SRStack.top();
1562 SRStack.pop();
1563
1564 if (const auto *FR = dyn_cast<FieldRegion>(TopR)) {
1565 OriginField = State->getLValue(FR->getDecl(), OriginField);
1566 } else if (const auto *ER = dyn_cast<ElementRegion>(TopR)) {
1567 OriginField = State->getLValue(ER->getElementType(),
1568 ER->getIndex(), OriginField);
1569 } else {
1570 // FIXME: handle other region type
1571 }
1572 }
1573
1574 // Track 'b.y.e'.
1575 getParentTracker().track(V, OriginField.getAsRegion(), Options);
1576 InitE = OriginEx;
1577 }
1578 }
1579 // This branch can occur in cases like `Ctor() : field{ x, y } {}'.
1580 else if (const auto *ILE = P->getStmtAs<InitListExpr>()) {
1581 // FIXME: Here we only track the top level region, so we lose
1582 // information, but it's still better than a crash or no information
1583 // at all.
1584 //
1585 // E.g.: The region we have is 's.s2.s3.s4.y' and we only track 'y', and
1586 // throw away the rest.
1587 InitE = tryExtractInitializerFromList(ILE, R);
1588 }
1589 }
1590
1591 // If this is a call entry, the variable should be a parameter.
1592 // FIXME: Handle CXXThisRegion as well. (This is not a priority because
1593 // 'this' should never be NULL, but this visitor isn't just for NULL and
1594 // UndefinedVal.)
1595 if (std::optional<CallEnter> CE = Succ->getLocationAs<CallEnter>()) {
1596 if (const auto *VR = dyn_cast<VarRegion>(R)) {
1597
1598 if (const auto *Param = dyn_cast<ParmVarDecl>(VR->getDecl())) {
1599 ProgramStateManager &StateMgr = BRC.getStateManager();
1600 CallEventManager &CallMgr = StateMgr.getCallEventManager();
1601
1603 CallMgr.getCaller(CE->getCalleeStackFrame(), Succ->getState());
1604 InitE = Call->getArgExpr(Param->getFunctionScopeIndex());
1605 } else {
1606 // Handle Objective-C 'self'.
1607 assert(isa<ImplicitParamDecl>(VR->getDecl()));
1608 InitE =
1609 cast<ObjCMessageExpr>(CE->getCalleeStackFrame()->getCallSite())
1610 ->getInstanceReceiver()
1611 ->IgnoreParenCasts();
1612 }
1613 IsParam = true;
1614 }
1615 }
1616
1617 // If this is a CXXTempObjectRegion, the Expr responsible for its creation
1618 // is wrapped inside of it.
1619 if (const auto *TmpR = dyn_cast<CXXTempObjectRegion>(R))
1620 InitE = TmpR->getExpr();
1621 }
1622
1623 if (!StoreSite)
1624 return nullptr;
1625
1626 Satisfied = true;
1627
1628 // If we have an expression that provided the value, try to track where it
1629 // came from.
1630 if (InitE) {
1631 if (!IsParam)
1632 InitE = InitE->IgnoreParenCasts();
1633
1634 getParentTracker().track(InitE, StoreSite, Options);
1635 }
1636
1637 // Let's try to find the region where the value came from.
1638 const MemRegion *OldRegion = nullptr;
1639
1640 // If we have init expression, it might be simply a reference
1641 // to a variable, so we can use it.
1642 if (InitE) {
1643 // That region might still be not exactly what we are looking for.
1644 // In situations like `int &ref = val;`, we can't say that
1645 // `ref` is initialized with `val`, rather refers to `val`.
1646 //
1647 // In order, to mitigate situations like this, we check if the last
1648 // stored value in that region is the value that we track.
1649 //
1650 // TODO: support other situations better.
1651 if (const MemRegion *Candidate =
1652 getLocationRegionIfReference(InitE, Succ, false)) {
1654
1655 // Here we traverse the graph up to find the last node where the
1656 // candidate region is still in the store.
1657 for (const ExplodedNode *N = StoreSite; N; N = N->getFirstPred()) {
1658 if (SM.includedInBindings(N->getState()->getStore(), Candidate)) {
1659 // And if it was bound to the target value, we can use it.
1660 if (N->getState()->getSVal(Candidate) == V) {
1661 OldRegion = Candidate;
1662 }
1663 break;
1664 }
1665 }
1666 }
1667 }
1668
1669 // Otherwise, if the current region does indeed contain the value
1670 // we are looking for, we can look for a region where this value
1671 // was before.
1672 //
1673 // It can be useful for situations like:
1674 // new = identity(old)
1675 // where the analyzer knows that 'identity' returns the value of its
1676 // first argument.
1677 //
1678 // NOTE: If the region R is not a simple var region, it can contain
1679 // V in one of its subregions.
1680 if (!OldRegion && StoreSite->getState()->getSVal(R) == V) {
1681 // Let's go up the graph to find the node where the region is
1682 // bound to V.
1683 const ExplodedNode *NodeWithoutBinding = StoreSite->getFirstPred();
1684 for (;
1685 NodeWithoutBinding && NodeWithoutBinding->getState()->getSVal(R) == V;
1686 NodeWithoutBinding = NodeWithoutBinding->getFirstPred()) {
1687 }
1688
1689 if (NodeWithoutBinding) {
1690 // Let's try to find a unique binding for the value in that node.
1691 // We want to use this to find unique bindings because of the following
1692 // situations:
1693 // b = a;
1694 // c = identity(b);
1695 //
1696 // Telling the user that the value of 'a' is assigned to 'c', while
1697 // correct, can be confusing.
1698 StoreManager::FindUniqueBinding FB(V.getAsLocSymbol());
1699 BRC.getStateManager().iterBindings(NodeWithoutBinding->getState(), FB);
1700 if (FB)
1701 OldRegion = FB.getRegion();
1702 }
1703 }
1704
1705 if (Options.Kind == TrackingKind::Condition && OriginSF &&
1706 !OriginSF->isParentOf(StoreSite->getStackFrame()))
1707 return nullptr;
1708
1709 // Okay, we've found the binding. Emit an appropriate message.
1710 SmallString<256> sbuf;
1711 llvm::raw_svector_ostream os(sbuf);
1712
1713 StoreInfo SI = {StoreInfo::Assignment, // default kind
1714 StoreSite,
1715 InitE,
1716 V,
1717 R,
1718 OldRegion};
1719
1720 if (std::optional<PostStmt> PS = StoreSite->getLocationAs<PostStmt>()) {
1721 const Stmt *S = PS->getStmt();
1722 const auto *DS = dyn_cast<DeclStmt>(S);
1723 const auto *VR = dyn_cast<VarRegion>(R);
1724
1725 if (DS) {
1727 } else if (const auto *BExpr = dyn_cast<BlockExpr>(S)) {
1729 if (VR) {
1730 // See if we can get the BlockVarRegion.
1731 ProgramStateRef State = StoreSite->getState();
1732 SVal V = StoreSite->getSVal(BExpr);
1733 if (const auto *BDR =
1734 dyn_cast_or_null<BlockDataRegion>(V.getAsRegion())) {
1735 if (const VarRegion *OriginalR = BDR->getOriginalRegion(VR)) {
1736 getParentTracker().track(State->getSVal(OriginalR), OriginalR,
1737 Options, OriginSF);
1738 }
1739 }
1740 }
1741 }
1742 } else if (SI.StoreSite->getLocation().getAs<CallEnter>() &&
1743 isa<VarRegion>(SI.Dest)) {
1745 }
1746
1747 return getParentTracker().handle(SI, BRC, Options);
1748}
1749
1750//===----------------------------------------------------------------------===//
1751// Implementation of TrackConstraintBRVisitor.
1752//===----------------------------------------------------------------------===//
1753
1754void TrackConstraintBRVisitor::Profile(llvm::FoldingSetNodeID &ID) const {
1755 static int tag = 0;
1756 ID.AddPointer(&tag);
1757 ID.AddString(Message);
1758 ID.AddBoolean(Assumption);
1759 ID.Add(Constraint);
1760}
1761
1762/// Return the tag associated with this visitor. This tag will be used
1763/// to make all PathDiagnosticPieces created by this visitor.
1765 return "TrackConstraintBRVisitor";
1766}
1767
1768bool TrackConstraintBRVisitor::isZeroCheck() const {
1769 return !Assumption && Constraint.getAs<Loc>();
1770}
1771
1772bool TrackConstraintBRVisitor::isUnderconstrained(const ExplodedNode *N) const {
1773 if (isZeroCheck())
1774 return N->getState()->isNull(Constraint).isUnderconstrained();
1775 return (bool)N->getState()->assume(Constraint, !Assumption);
1776}
1777
1780 const ExplodedNode *PrevN = N->getFirstPred();
1781 if (IsSatisfied)
1782 return nullptr;
1783
1784 // Start tracking after we see the first state in which the value is
1785 // constrained.
1786 if (!IsTrackingTurnedOn)
1787 if (!isUnderconstrained(N))
1788 IsTrackingTurnedOn = true;
1789 if (!IsTrackingTurnedOn)
1790 return nullptr;
1791
1792 // Check if in the previous state it was feasible for this constraint
1793 // to *not* be true.
1794 if (isUnderconstrained(PrevN)) {
1795 IsSatisfied = true;
1796
1797 // At this point, the negation of the constraint should be infeasible. If it
1798 // is feasible, make sure that the negation of the constrainti was
1799 // infeasible in the current state. If it is feasible, we somehow missed
1800 // the transition point.
1801 assert(!isUnderconstrained(N));
1802
1803 // Construct a new PathDiagnosticPiece.
1804 ProgramPoint P = N->getLocation();
1805
1806 // If this node already have a specialized note, it's probably better
1807 // than our generic note.
1808 // FIXME: This only looks for note tags, not for other ways to add a note.
1809 if (isa_and_nonnull<NoteTag>(P.getTag()))
1810 return nullptr;
1811
1814 if (!L.isValid())
1815 return nullptr;
1816
1817 auto X = std::make_shared<PathDiagnosticEventPiece>(L, Message);
1818 X->setTag(getTag());
1819 return std::move(X);
1820 }
1821
1822 return nullptr;
1823}
1824
1825//===----------------------------------------------------------------------===//
1826// Implementation of SuppressInlineDefensiveChecksVisitor.
1827//===----------------------------------------------------------------------===//
1828
1831 : V(Value) {
1832 // Check if the visitor is disabled.
1833 AnalyzerOptions &Options = N->getState()->getAnalysisManager().options;
1834 if (!Options.ShouldSuppressInlinedDefensiveChecks)
1835 IsSatisfied = true;
1836}
1837
1839 llvm::FoldingSetNodeID &ID) const {
1840 static int id = 0;
1841 ID.AddPointer(&id);
1842 ID.Add(V);
1843}
1844
1846 return "IDCVisitor";
1847}
1848
1851 BugReporterContext &BRC,
1853 const ExplodedNode *Pred = Succ->getFirstPred();
1854 if (IsSatisfied)
1855 return nullptr;
1856
1857 // Start tracking after we see the first state in which the value is null.
1858 if (!IsTrackingTurnedOn)
1859 if (Succ->getState()->isNull(V).isConstrainedTrue())
1860 IsTrackingTurnedOn = true;
1861 if (!IsTrackingTurnedOn)
1862 return nullptr;
1863
1864 // Check if in the previous state it was feasible for this value
1865 // to *not* be null.
1866 if (!Pred->getState()->isNull(V).isConstrainedTrue() &&
1867 Succ->getState()->isNull(V).isConstrainedTrue()) {
1868 IsSatisfied = true;
1869
1870 // Check if this is inlined defensive checks.
1871 const StackFrame *CurSF = Succ->getStackFrame();
1872 const StackFrame *ReportSF = BR.getErrorNode()->getStackFrame();
1873 if (CurSF != ReportSF && !CurSF->isParentOf(ReportSF)) {
1874 BR.markInvalid("Suppress IDC", CurSF);
1875 return nullptr;
1876 }
1877
1878 // Treat defensive checks in function-like macros as if they were an inlined
1879 // defensive check. If the bug location is not in a macro and the
1880 // terminator for the current location is in a macro then suppress the
1881 // warning.
1882 auto BugPoint = BR.getErrorNode()->getLocation().getAs<StmtPoint>();
1883
1884 if (!BugPoint)
1885 return nullptr;
1886
1887 ProgramPoint CurPoint = Succ->getLocation();
1888 const Stmt *CurTerminatorStmt = nullptr;
1889 if (auto BE = CurPoint.getAs<BlockEdge>()) {
1890 CurTerminatorStmt = BE->getSrc()->getTerminator().getStmt();
1891 } else if (auto SP = CurPoint.getAs<StmtPoint>()) {
1892 const Stmt *CurStmt = SP->getStmt();
1893 if (!CurStmt->getBeginLoc().isMacroID())
1894 return nullptr;
1895
1896 const CFGStmtMap *Map = CurSF->getAnalysisDeclContext()->getCFGStmtMap();
1897 CurTerminatorStmt = Map->getBlock(CurStmt)->getTerminatorStmt();
1898 } else {
1899 return nullptr;
1900 }
1901
1902 if (!CurTerminatorStmt)
1903 return nullptr;
1904
1905 SourceLocation TerminatorLoc = CurTerminatorStmt->getBeginLoc();
1906 if (TerminatorLoc.isMacroID()) {
1907 SourceLocation BugLoc = BugPoint->getStmt()->getBeginLoc();
1908
1909 // Suppress reports unless we are in that same macro.
1910 if (!BugLoc.isMacroID() ||
1911 getMacroName(BugLoc, BRC) != getMacroName(TerminatorLoc, BRC)) {
1912 BR.markInvalid("Suppress Macro IDC", CurSF);
1913 }
1914 return nullptr;
1915 }
1916 }
1917 return nullptr;
1918}
1919
1920//===----------------------------------------------------------------------===//
1921// TrackControlDependencyCondBRVisitor.
1922//===----------------------------------------------------------------------===//
1923
1924namespace {
1925/// Tracks the expressions that are a control dependency of the node that was
1926/// supplied to the constructor.
1927/// For example:
1928///
1929/// cond = 1;
1930/// if (cond)
1931/// 10 / 0;
1932///
1933/// An error is emitted at line 3. This visitor realizes that the branch
1934/// on line 2 is a control dependency of line 3, and tracks it's condition via
1935/// trackExpressionValue().
1936class TrackControlDependencyCondBRVisitor final
1938 const ExplodedNode *Origin;
1939 ControlDependencyCalculator ControlDeps;
1941
1942public:
1943 TrackControlDependencyCondBRVisitor(TrackerRef ParentTracker,
1944 const ExplodedNode *O)
1945 : TrackingBugReporterVisitor(ParentTracker), Origin(O),
1946 ControlDeps(&O->getCFG()) {}
1947
1948 void Profile(llvm::FoldingSetNodeID &ID) const override {
1949 static int x = 0;
1950 ID.AddPointer(&x);
1951 }
1952
1953 PathDiagnosticPieceRef VisitNode(const ExplodedNode *N,
1954 BugReporterContext &BRC,
1955 PathSensitiveBugReport &BR) override;
1956};
1957} // end of anonymous namespace
1958
1959static std::shared_ptr<PathDiagnosticEventPiece>
1961 const ExplodedNode *N,
1962 BugReporterContext &BRC) {
1963
1965 !BRC.getAnalyzerOptions().ShouldTrackConditionsDebug)
1966 return nullptr;
1967
1968 std::string ConditionText = std::string(Lexer::getSourceText(
1969 CharSourceRange::getTokenRange(Cond->getSourceRange()),
1971
1972 return std::make_shared<PathDiagnosticEventPiece>(
1974 N->getStackFrame()),
1975 (Twine() + "Tracking condition '" + ConditionText + "'").str());
1976}
1977
1978static bool isAssertlikeBlock(const CFGBlock *B, ASTContext &Context) {
1979 if (B->succ_size() != 2)
1980 return false;
1981
1982 const CFGBlock *Then = B->succ_begin()->getReachableBlock();
1983 const CFGBlock *Else = (B->succ_begin() + 1)->getReachableBlock();
1984
1985 if (!Then || !Else)
1986 return false;
1987
1988 if (Then->isInevitablySinking() != Else->isInevitablySinking())
1989 return true;
1990
1991 // For the following condition the following CFG would be built:
1992 //
1993 // ------------->
1994 // / \
1995 // [B1] -> [B2] -> [B3] -> [sink]
1996 // assert(A && B || C); \ \
1997 // -----------> [go on with the execution]
1998 //
1999 // It so happens that CFGBlock::getTerminatorCondition returns 'A' for block
2000 // B1, 'A && B' for B2, and 'A && B || C' for B3. Let's check whether we
2001 // reached the end of the condition!
2002 if (const Stmt *ElseCond = Else->getTerminatorCondition())
2003 if (const auto *BinOp = dyn_cast<BinaryOperator>(ElseCond))
2004 if (BinOp->isLogicalOp())
2005 return isAssertlikeBlock(Else, Context);
2006
2007 return false;
2008}
2009
2011TrackControlDependencyCondBRVisitor::VisitNode(const ExplodedNode *N,
2012 BugReporterContext &BRC,
2014 // We can only reason about control dependencies within the same stack frame.
2015 if (Origin->getStackFrame() != N->getStackFrame())
2016 return nullptr;
2017
2018 CFGBlock *NB = const_cast<CFGBlock *>(N->getCFGBlock());
2019
2020 // Skip if we already inspected this block.
2021 if (!VisitedBlocks.insert(NB).second)
2022 return nullptr;
2023
2024 CFGBlock *OriginB = const_cast<CFGBlock *>(Origin->getCFGBlock());
2025
2026 // TODO: Cache CFGBlocks for each ExplodedNode.
2027 if (!OriginB || !NB)
2028 return nullptr;
2029
2030 if (isAssertlikeBlock(NB, BRC.getASTContext()))
2031 return nullptr;
2032
2033 if (ControlDeps.isControlDependent(OriginB, NB)) {
2034 // We don't really want to explain for range loops. Evidence suggests that
2035 // the only thing that leads to is the addition of calls to operator!=.
2036 if (llvm::isa_and_nonnull<CXXForRangeStmt>(NB->getTerminatorStmt()))
2037 return nullptr;
2038
2039 if (const Expr *Condition = NB->getLastCondition()) {
2040
2041 // If we can't retrieve a sensible condition, just bail out.
2042 const Expr *InnerExpr = peelOffOuterExpr(Condition, N);
2043 if (!InnerExpr)
2044 return nullptr;
2045
2046 // If the condition was a function call, we likely won't gain much from
2047 // tracking it either. Evidence suggests that it will mostly trigger in
2048 // scenarios like this:
2049 //
2050 // void f(int *x) {
2051 // x = nullptr;
2052 // if (alwaysTrue()) // We don't need a whole lot of explanation
2053 // // here, the function name is good enough.
2054 // *x = 5;
2055 // }
2056 //
2057 // Its easy to create a counterexample where this heuristic would make us
2058 // lose valuable information, but we've never really seen one in practice.
2059 if (isa<CallExpr>(InnerExpr))
2060 return nullptr;
2061
2062 // Keeping track of the already tracked conditions on a visitor level
2063 // isn't sufficient, because a new visitor is created for each tracked
2064 // expression, hence the BugReport level set.
2065 if (BR.addTrackedCondition(N)) {
2066 getParentTracker().track(InnerExpr, N,
2068 /*EnableNullFPSuppression=*/false});
2070 }
2071 }
2072 }
2073
2074 return nullptr;
2075}
2076
2077//===----------------------------------------------------------------------===//
2078// Implementation of trackExpressionValue.
2079//===----------------------------------------------------------------------===//
2080
2081static const Expr *peelOffOuterExpr(const Expr *Ex, const ExplodedNode *N) {
2082
2083 Ex = Ex->IgnoreParenCasts();
2084 if (const auto *FE = dyn_cast<FullExpr>(Ex))
2085 return peelOffOuterExpr(FE->getSubExpr(), N);
2086 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(Ex))
2087 return peelOffOuterExpr(OVE->getSourceExpr(), N);
2088 if (const auto *POE = dyn_cast<PseudoObjectExpr>(Ex)) {
2089 const auto *PropRef = dyn_cast<ObjCPropertyRefExpr>(POE->getSyntacticForm());
2090 if (PropRef && PropRef->isMessagingGetter()) {
2091 const Expr *GetterMessageSend =
2092 POE->getSemanticExpr(POE->getNumSemanticExprs() - 1);
2093 assert(isa<ObjCMessageExpr>(GetterMessageSend->IgnoreParenCasts()));
2094 return peelOffOuterExpr(GetterMessageSend, N);
2095 }
2096 }
2097
2098 // Peel off the ternary operator.
2099 if (const auto *CO = dyn_cast<ConditionalOperator>(Ex)) {
2100 // Find a node where the branching occurred and find out which branch
2101 // we took (true/false) by looking at the ExplodedGraph.
2102 const ExplodedNode *NI = N;
2103 do {
2104 ProgramPoint ProgPoint = NI->getLocation();
2105 if (std::optional<BlockEdge> BE = ProgPoint.getAs<BlockEdge>()) {
2106 const CFGBlock *srcBlk = BE->getSrc();
2107 if (const Stmt *term = srcBlk->getTerminatorStmt()) {
2108 if (term == CO) {
2109 bool TookTrueBranch = (*(srcBlk->succ_begin()) == BE->getDst());
2110 if (TookTrueBranch)
2111 return peelOffOuterExpr(CO->getTrueExpr(), N);
2112 else
2113 return peelOffOuterExpr(CO->getFalseExpr(), N);
2114 }
2115 }
2116 }
2117 NI = NI->getFirstPred();
2118 } while (NI);
2119 }
2120
2121 if (auto *BO = dyn_cast<BinaryOperator>(Ex))
2122 if (const Expr *SubEx = peelOffPointerArithmetic(BO))
2123 return peelOffOuterExpr(SubEx, N);
2124
2125 if (auto *UO = dyn_cast<UnaryOperator>(Ex)) {
2126 if (UO->getOpcode() == UO_LNot)
2127 return peelOffOuterExpr(UO->getSubExpr(), N);
2128
2129 // FIXME: There's a hack in our Store implementation that always computes
2130 // field offsets around null pointers as if they are always equal to 0.
2131 // The idea here is to report accesses to fields as null dereferences
2132 // even though the pointer value that's being dereferenced is actually
2133 // the offset of the field rather than exactly 0.
2134 // See the FIXME in StoreManager's getLValueFieldOrIvar() method.
2135 // This code interacts heavily with this hack; otherwise the value
2136 // would not be null at all for most fields, so we'd be unable to track it.
2137 if (UO->getOpcode() == UO_AddrOf && UO->getSubExpr()->isLValue())
2138 if (const Expr *DerefEx = bugreporter::getDerefExpr(UO->getSubExpr()))
2139 return peelOffOuterExpr(DerefEx, N);
2140 }
2141
2142 return Ex;
2143}
2144
2145/// Find the ExplodedNode where the lvalue (the value of 'Ex')
2146/// was computed.
2148 const Expr *Inner) {
2149 while (N) {
2150 if (N->getStmtForDiagnostics() == Inner)
2151 return N;
2152 N = N->getFirstPred();
2153 }
2154 return N;
2155}
2156
2157//===----------------------------------------------------------------------===//
2158// Tracker implementation
2159//===----------------------------------------------------------------------===//
2160
2162 BugReporterContext &BRC,
2163 StringRef NodeText) {
2164 // Construct a new PathDiagnosticPiece.
2167 if (P.getAs<CallEnter>() && SI.SourceOfTheValue)
2169 P.getStackFrame());
2170
2171 if (!L.isValid() || !L.asLocation().isValid())
2173
2174 if (!L.isValid() || !L.asLocation().isValid())
2175 return nullptr;
2176
2177 return std::make_shared<PathDiagnosticEventPiece>(L, NodeText);
2178}
2179
2180namespace {
2181class DefaultStoreHandler final : public StoreHandler {
2182public:
2184
2186 TrackingOptions Opts) override {
2187 // Okay, we've found the binding. Emit an appropriate message.
2188 SmallString<256> Buffer;
2189 llvm::raw_svector_ostream OS(Buffer);
2190
2191 switch (SI.StoreKind) {
2194 showBRDiagnostics(OS, SI);
2195 break;
2198 break;
2201 break;
2202 }
2203
2206
2207 return constructNote(SI, BRC, OS.str());
2208 }
2209};
2210
2211class ControlDependencyHandler final : public ExpressionHandler {
2212public:
2214
2215 Tracker::Result handle(const Expr *Inner, const ExplodedNode *InputNode,
2216 const ExplodedNode *LVNode,
2217 TrackingOptions Opts) override {
2218 PathSensitiveBugReport &Report = getParentTracker().getReport();
2219
2220 // We only track expressions if we believe that they are important. Chances
2221 // are good that control dependencies to the tracking point are also
2222 // important because of this, let's explain why we believe control reached
2223 // this point.
2224 // TODO: Shouldn't we track control dependencies of every bug location,
2225 // rather than only tracked expressions?
2226 if (LVNode->getState()
2227 ->getAnalysisManager()
2228 .getAnalyzerOptions()
2229 .ShouldTrackConditions) {
2230 Report.addVisitor<TrackControlDependencyCondBRVisitor>(
2231 &getParentTracker(), InputNode);
2232 return {/*FoundSomethingToTrack=*/true};
2233 }
2234
2235 return {};
2236 }
2237};
2238
2239class NilReceiverHandler final : public ExpressionHandler {
2240public:
2242
2243 Tracker::Result handle(const Expr *Inner, const ExplodedNode *InputNode,
2244 const ExplodedNode *LVNode,
2245 TrackingOptions Opts) override {
2246 // The message send could be nil due to the receiver being nil.
2247 // At this point in the path, the receiver should be live since we are at
2248 // the message send expr. If it is nil, start tracking it.
2249 if (const Expr *Receiver =
2251 return getParentTracker().track(Receiver, LVNode, Opts);
2252
2253 return {};
2254 }
2255};
2256
2257class ArrayIndexHandler final : public ExpressionHandler {
2258public:
2260
2261 Tracker::Result handle(const Expr *Inner, const ExplodedNode *InputNode,
2262 const ExplodedNode *LVNode,
2263 TrackingOptions Opts) override {
2264 // Track the index if this is an array subscript.
2265 if (const auto *Arr = dyn_cast<ArraySubscriptExpr>(Inner))
2266 return getParentTracker().track(
2267 Arr->getIdx(), LVNode,
2268 {Opts.Kind, /*EnableNullFPSuppression*/ false});
2269
2270 return {};
2271 }
2272};
2273
2274// TODO: extract it into more handlers
2275class InterestingLValueHandler final : public ExpressionHandler {
2276public:
2278
2279 Tracker::Result handle(const Expr *Inner, const ExplodedNode *InputNode,
2280 const ExplodedNode *LVNode,
2281 TrackingOptions Opts) override {
2282 ProgramStateRef LVState = LVNode->getState();
2283 const StackFrame *SF = LVNode->getStackFrame();
2284 PathSensitiveBugReport &Report = getParentTracker().getReport();
2285 Tracker::Result Result;
2286
2287 // See if the expression we're interested refers to a variable.
2288 // If so, we can track both its contents and constraints on its value.
2290 SVal LVal = LVNode->getSVal(Inner);
2291
2292 const MemRegion *RR = getLocationRegionIfReference(Inner, LVNode);
2293 bool LVIsNull = LVState->isNull(LVal).isConstrainedTrue();
2294
2295 // If this is a C++ reference to a null pointer, we are tracking the
2296 // pointer. In addition, we should find the store at which the reference
2297 // got initialized.
2298 if (RR && !LVIsNull)
2299 Result.combineWith(getParentTracker().track(LVal, RR, Opts, SF));
2300
2301 // In case of C++ references, we want to differentiate between a null
2302 // reference and reference to null pointer.
2303 // If the LVal is null, check if we are dealing with null reference.
2304 // For those, we want to track the location of the reference.
2305 const MemRegion *R =
2306 (RR && LVIsNull) ? RR : LVNode->getSVal(Inner).getAsRegion();
2307
2308 if (R) {
2309
2310 // Mark both the variable region and its contents as interesting.
2311 SVal V = LVState->getRawSVal(loc::MemRegionVal(R));
2312 Report.addVisitor<NoStoreFuncVisitor>(cast<SubRegion>(R), Opts.Kind);
2313
2314 // When we got here, we do have something to track, and we will
2315 // interrupt.
2316 Result.FoundSomethingToTrack = true;
2317 Result.WasInterrupted = true;
2318
2319 MacroNullReturnSuppressionVisitor::addMacroVisitorIfNecessary(
2320 LVNode, R, Opts.EnableNullFPSuppression, Report, V);
2321
2322 Report.markInteresting(V, Opts.Kind);
2323 Report.addVisitor<UndefOrNullArgVisitor>(R);
2324
2325 // If the contents are symbolic and null, find out when they became
2326 // null.
2327 if (V.getAsLocSymbol(/*IncludeBaseRegions=*/true))
2328 if (LVState->isNull(V).isConstrainedTrue())
2329 Report.addVisitor<TrackConstraintBRVisitor>(
2330 V.castAs<DefinedSVal>(),
2331 /*Assumption=*/false, "Assuming pointer value is null");
2332
2333 // Add visitor, which will suppress inline defensive checks.
2334 if (auto DV = V.getAs<DefinedSVal>())
2335 if (!DV->isZeroConstant() && Opts.EnableNullFPSuppression)
2336 // Note that LVNode may be too late (i.e., too far from the
2337 // InputNode) because the lvalue may have been computed before the
2338 // inlined call was evaluated. InputNode may as well be too early
2339 // here, because the symbol is already dead; this, however, is fine
2340 // because we can still find the node in which it collapsed to null
2341 // previously.
2342 Report.addVisitor<SuppressInlineDefensiveChecksVisitor>(*DV,
2343 InputNode);
2344 getParentTracker().track(V, R, Opts, SF);
2345 }
2346 }
2347
2348 return Result;
2349 }
2350};
2351
2352/// Adds a ReturnVisitor if the given statement represents a call that was
2353/// inlined.
2354///
2355/// This will search back through the ExplodedGraph, starting from the given
2356/// node, looking for when the given statement was processed. If it turns out
2357/// the statement is a call that was inlined, we add the visitor to the
2358/// bug report, so it can print a note later.
2359class InlinedFunctionCallHandler final : public ExpressionHandler {
2361
2362 Tracker::Result handle(const Expr *E, const ExplodedNode *InputNode,
2363 const ExplodedNode *ExprNode,
2364 TrackingOptions Opts) override {
2365 if (!CallEvent::isCallStmt(E))
2366 return {};
2367
2368 // First, find when we processed the statement.
2369 // If we work with a 'CXXNewExpr' that is going to be purged away before
2370 // its call take place. We would catch that purge in the last condition
2371 // as a 'StmtPoint' so we have to bypass it.
2372 const bool BypassCXXNewExprEval = isa<CXXNewExpr>(E);
2373
2374 // This is moving forward when we enter into another stack frame.
2375 const StackFrame *CurrentSF = ExprNode->getStackFrame();
2376
2377 do {
2378 // If that is satisfied we found our statement as an inlined call.
2379 if (std::optional<CallExitEnd> CEE =
2380 ExprNode->getLocationAs<CallExitEnd>())
2381 if (CEE->getCalleeStackFrame()->getCallSite() == E)
2382 break;
2383
2384 // Try to move forward to the end of the call-chain.
2385 ExprNode = ExprNode->getFirstPred();
2386 if (!ExprNode)
2387 break;
2388
2389 const StackFrame *PredSF = ExprNode->getStackFrame();
2390
2391 // If that is satisfied we found our statement.
2392 // FIXME: This code currently bypasses the call site for the
2393 // conservatively evaluated allocator.
2394 if (!BypassCXXNewExprEval)
2395 if (std::optional<StmtPoint> SP = ExprNode->getLocationAs<StmtPoint>())
2396 // See if we do not enter into another stack frame.
2397 if (SP->getStmt() == E && CurrentSF == PredSF)
2398 break;
2399
2400 CurrentSF = PredSF;
2401 } while (ExprNode->getStackFrame() == CurrentSF);
2402
2403 // Next, step over any post-statement checks.
2404 while (ExprNode && ExprNode->getLocation().getAs<PostStmt>())
2405 ExprNode = ExprNode->getFirstPred();
2406 if (!ExprNode)
2407 return {};
2408
2409 // Finally, see if we inlined the call.
2410 std::optional<CallExitEnd> CEE = ExprNode->getLocationAs<CallExitEnd>();
2411 if (!CEE)
2412 return {};
2413
2414 const StackFrame *CalleeSF = CEE->getCalleeStackFrame();
2415 if (CalleeSF->getCallSite() != E)
2416 return {};
2417
2418 // Check the return value.
2419 ProgramStateRef State = ExprNode->getState();
2420 SVal RetVal = ExprNode->getSVal(E);
2421
2422 // Handle cases where a reference is returned and then immediately used.
2423 if (cast<Expr>(E)->isGLValue())
2424 if (std::optional<Loc> LValue = RetVal.getAs<Loc>())
2425 RetVal = State->getSVal(*LValue);
2426
2427 // See if the return value is NULL. If so, suppress the report.
2428 AnalyzerOptions &Options = State->getAnalysisManager().options;
2429
2430 bool EnableNullFPSuppression = false;
2431 if (Opts.EnableNullFPSuppression && Options.ShouldSuppressNullReturnPaths)
2432 if (std::optional<Loc> RetLoc = RetVal.getAs<Loc>())
2433 EnableNullFPSuppression = State->isNull(*RetLoc).isConstrainedTrue();
2434
2435 PathSensitiveBugReport &Report = getParentTracker().getReport();
2436 Report.addVisitor<ReturnVisitor>(&getParentTracker(), CalleeSF,
2437 EnableNullFPSuppression, Options,
2438 Opts.Kind);
2439 return {true};
2440 }
2441};
2442
2443class DefaultExpressionHandler final : public ExpressionHandler {
2444public:
2446
2447 Tracker::Result handle(const Expr *Inner, const ExplodedNode *InputNode,
2448 const ExplodedNode *LVNode,
2449 TrackingOptions Opts) override {
2450 ProgramStateRef LVState = LVNode->getState();
2451 const StackFrame *SF = LVNode->getStackFrame();
2452 PathSensitiveBugReport &Report = getParentTracker().getReport();
2453 Tracker::Result Result;
2454
2455 // If the expression is not an "lvalue expression", we can still
2456 // track the constraints on its contents.
2457 SVal V = LVState->getSValAsScalarOrLoc(Inner, LVNode->getStackFrame());
2458
2459 // Is it a symbolic value?
2460 if (auto L = V.getAs<loc::MemRegionVal>()) {
2461 // FIXME: this is a hack for fixing a later crash when attempting to
2462 // dereference a void* pointer.
2463 // We should not try to dereference pointers at all when we don't care
2464 // what is written inside the pointer.
2465 bool CanDereference = true;
2466 if (const auto *SR = L->getRegionAs<SymbolicRegion>()) {
2467 if (SR->getPointeeStaticType()->isVoidType())
2468 CanDereference = false;
2469 } else if (L->getRegionAs<AllocaRegion>())
2470 CanDereference = false;
2471
2472 // At this point we are dealing with the region's LValue.
2473 // However, if the rvalue is a symbolic region, we should track it as
2474 // well. Try to use the correct type when looking up the value.
2475 SVal RVal;
2477 RVal = LVState->getRawSVal(*L, Inner->getType());
2478 else if (CanDereference)
2479 RVal = LVState->getSVal(L->getRegion());
2480
2481 if (CanDereference) {
2482 Report.addVisitor<UndefOrNullArgVisitor>(L->getRegion());
2483 Result.FoundSomethingToTrack = true;
2484
2485 if (!RVal.isUnknown())
2486 Result.combineWith(
2487 getParentTracker().track(RVal, L->getRegion(), Opts, SF));
2488 }
2489
2490 const MemRegion *RegionRVal = RVal.getAsRegion();
2491 if (isa_and_nonnull<SymbolicRegion>(RegionRVal)) {
2492 Report.markInteresting(RegionRVal, Opts.Kind);
2493 Report.addVisitor<TrackConstraintBRVisitor>(
2494 loc::MemRegionVal(RegionRVal),
2495 /*Assumption=*/false, "Assuming pointer value is null");
2496 Result.FoundSomethingToTrack = true;
2497 }
2498 }
2499
2500 return Result;
2501 }
2502};
2503
2504/// Attempts to add visitors to track an RValue expression back to its point of
2505/// origin.
2506class PRValueHandler final : public ExpressionHandler {
2507public:
2509
2510 Tracker::Result handle(const Expr *E, const ExplodedNode *InputNode,
2511 const ExplodedNode *ExprNode,
2512 TrackingOptions Opts) override {
2513 if (!E->isPRValue())
2514 return {};
2515
2516 const ExplodedNode *RVNode = findNodeForExpression(ExprNode, E);
2517 if (!RVNode)
2518 return {};
2519
2520 Tracker::Result CombinedResult;
2521 Tracker &Parent = getParentTracker();
2522
2523 const auto track = [&CombinedResult, &Parent, ExprNode,
2524 Opts](const Expr *Inner) {
2525 CombinedResult.combineWith(Parent.track(Inner, ExprNode, Opts));
2526 };
2527
2528 // FIXME: Initializer lists can appear in many different contexts
2529 // and most of them needs a special handling. For now let's handle
2530 // what we can. If the initializer list only has 1 element, we track
2531 // that.
2532 // This snippet even handles nesting, e.g.: int *x{{{{{y}}}}};
2533 if (const auto *ILE = dyn_cast<InitListExpr>(E)) {
2534 if (ILE->getNumInits() == 1) {
2535 track(ILE->getInit(0));
2536
2537 return CombinedResult;
2538 }
2539
2540 return {};
2541 }
2542
2543 ProgramStateRef RVState = RVNode->getState();
2544 SVal V = RVState->getSValAsScalarOrLoc(E, RVNode->getStackFrame());
2545 const auto *BO = dyn_cast<BinaryOperator>(E);
2546
2547 if (!BO || !BO->isMultiplicativeOp() || !V.isZeroConstant())
2548 return {};
2549
2550 SVal RHSV = RVState->getSVal(BO->getRHS(), RVNode->getStackFrame());
2551 SVal LHSV = RVState->getSVal(BO->getLHS(), RVNode->getStackFrame());
2552
2553 // Track both LHS and RHS of a multiplication.
2554 if (BO->getOpcode() == BO_Mul) {
2555 if (LHSV.isZeroConstant())
2556 track(BO->getLHS());
2557 if (RHSV.isZeroConstant())
2558 track(BO->getRHS());
2559 } else { // Track only the LHS of a division or a modulo.
2560 if (LHSV.isZeroConstant())
2561 track(BO->getLHS());
2562 }
2563
2564 return CombinedResult;
2565 }
2566};
2567} // namespace
2568
2581
2583 TrackingOptions Opts) {
2584 if (!E || !N)
2585 return {};
2586
2587 const Expr *Inner = peelOffOuterExpr(E, N);
2588 const ExplodedNode *LVNode = findNodeForExpression(N, Inner);
2589 if (!LVNode)
2590 return {};
2591
2592 Result CombinedResult;
2593 // Iterate through the handlers in the order according to their priorities.
2594 for (ExpressionHandlerPtr &Handler : ExpressionHandlers) {
2595 CombinedResult.combineWith(Handler->handle(Inner, N, LVNode, Opts));
2596 if (CombinedResult.WasInterrupted) {
2597 // There is no need to confuse our users here.
2598 // We got interrupted, but our users don't need to know about it.
2599 CombinedResult.WasInterrupted = false;
2600 break;
2601 }
2602 }
2603
2604 return CombinedResult;
2605}
2606
2608 const StackFrame *Origin) {
2609 if (!V.isUnknown()) {
2610 Report.addVisitor<StoreSiteFinder>(this, V, R, Opts, Origin);
2611 return {true};
2612 }
2613 return {};
2614}
2615
2617 TrackingOptions Opts) {
2618 // Iterate through the handlers in the order according to their priorities.
2619 for (StoreHandlerPtr &Handler : StoreHandlers) {
2620 if (PathDiagnosticPieceRef Result = Handler->handle(SI, BRC, Opts))
2621 // If the handler produced a non-null piece, return it.
2622 // There is no need in asking other handlers.
2623 return Result;
2624 }
2625 return {};
2626}
2627
2629 const Expr *E,
2630
2632 TrackingOptions Opts) {
2633 return Tracker::create(Report)
2634 ->track(E, InputNode, Opts)
2635 .FoundSomethingToTrack;
2636}
2637
2640 TrackingOptions Opts,
2641 const StackFrame *Origin) {
2642 Tracker::create(Report)->track(V, R, Opts, Origin);
2643}
2644
2645//===----------------------------------------------------------------------===//
2646// Implementation of NulReceiverBRVisitor.
2647//===----------------------------------------------------------------------===//
2648
2650 const ExplodedNode *N) {
2651 const auto *ME = dyn_cast<ObjCMessageExpr>(S);
2652 if (!ME)
2653 return nullptr;
2654 if (const Expr *Receiver = ME->getInstanceReceiver()) {
2655 ProgramStateRef state = N->getState();
2656 SVal V = N->getSVal(Receiver);
2657 if (state->isNull(V).isConstrainedTrue())
2658 return Receiver;
2659 }
2660 return nullptr;
2661}
2662
2666 std::optional<PreStmt> P = N->getLocationAs<PreStmt>();
2667 if (!P)
2668 return nullptr;
2669
2670 const Stmt *S = P->getStmt();
2671 const Expr *Receiver = getNilReceiver(S, N);
2672 if (!Receiver)
2673 return nullptr;
2674
2676 llvm::raw_svector_ostream OS(Buf);
2677
2678 if (const auto *ME = dyn_cast<ObjCMessageExpr>(S)) {
2679 OS << "'";
2680 ME->getSelector().print(OS);
2681 OS << "' not called";
2682 }
2683 else {
2684 OS << "No method is called";
2685 }
2686 OS << " because the receiver is nil";
2687
2688 // The receiver was nil, and hence the method was skipped.
2689 // Register a BugReporterVisitor to issue a message telling us how
2690 // the receiver was null.
2691 bugreporter::trackExpressionValue(N, Receiver, BR,
2693 /*EnableNullFPSuppression*/ false});
2694 // Issue a message saying that the method was skipped.
2695 PathDiagnosticLocation L(Receiver, BRC.getSourceManager(),
2696 N->getStackFrame());
2697 return std::make_shared<PathDiagnosticEventPiece>(L, OS.str());
2698}
2699
2700//===----------------------------------------------------------------------===//
2701// Visitor that tries to report interesting diagnostics from conditions.
2702//===----------------------------------------------------------------------===//
2703
2704/// Return the tag associated with this visitor. This tag will be used
2705/// to make all PathDiagnosticPieces created by this visitor.
2706const char *ConditionBRVisitor::getTag() { return "ConditionBRVisitor"; }
2707
2711 auto piece = VisitNodeImpl(N, BRC, BR);
2712 if (piece) {
2713 piece->setTag(getTag());
2714 if (auto *ev = dyn_cast<PathDiagnosticEventPiece>(piece.get()))
2715 ev->setPrunable(true, /* override */ false);
2716 }
2717 return piece;
2718}
2719
2722 BugReporterContext &BRC,
2724 ProgramPoint ProgPoint = N->getLocation();
2725 const std::pair<const ProgramPointTag *, const ProgramPointTag *> &Tags =
2727
2728 // If an assumption was made on a branch, it should be caught
2729 // here by looking at the state transition.
2730 if (std::optional<BlockEdge> BE = ProgPoint.getAs<BlockEdge>()) {
2731 const CFGBlock *SrcBlock = BE->getSrc();
2732 if (const Stmt *Term = SrcBlock->getTerminatorStmt()) {
2733 // If the tag of the previous node is 'Eagerly Assume...' the current
2734 // 'BlockEdge' has the same constraint information. We do not want to
2735 // report the value as it is just an assumption on the predecessor node
2736 // which will be caught in the next VisitNode() iteration as a 'PostStmt'.
2737 const ProgramPointTag *PreviousNodeTag =
2739 if (PreviousNodeTag == Tags.first || PreviousNodeTag == Tags.second)
2740 return nullptr;
2741
2742 return VisitTerminator(Term, N, SrcBlock, BE->getDst(), BR, BRC);
2743 }
2744 return nullptr;
2745 }
2746
2747 if (std::optional<PostStmt> PS = ProgPoint.getAs<PostStmt>()) {
2748 const ProgramPointTag *CurrentNodeTag = PS->getTag();
2749 if (CurrentNodeTag != Tags.first && CurrentNodeTag != Tags.second)
2750 return nullptr;
2751
2752 bool TookTrue = CurrentNodeTag == Tags.first;
2753 return VisitTrueTest(cast<Expr>(PS->getStmt()), BRC, BR, N, TookTrue);
2754 }
2755
2756 return nullptr;
2757}
2758
2760 const Stmt *Term, const ExplodedNode *N, const CFGBlock *srcBlk,
2761 const CFGBlock *dstBlk, PathSensitiveBugReport &R,
2762 BugReporterContext &BRC) {
2763 const Expr *Cond = nullptr;
2764
2765 // In the code below, Term is a CFG terminator and Cond is a branch condition
2766 // expression upon which the decision is made on this terminator.
2767 //
2768 // For example, in "if (x == 0)", the "if (x == 0)" statement is a terminator,
2769 // and "x == 0" is the respective condition.
2770 //
2771 // Another example: in "if (x && y)", we've got two terminators and two
2772 // conditions due to short-circuit nature of operator "&&":
2773 // 1. The "if (x && y)" statement is a terminator,
2774 // and "y" is the respective condition.
2775 // 2. Also "x && ..." is another terminator,
2776 // and "x" is its condition.
2777
2778 switch (Term->getStmtClass()) {
2779 // FIXME: Stmt::SwitchStmtClass is worth handling, however it is a bit
2780 // more tricky because there are more than two branches to account for.
2781 default:
2782 return nullptr;
2783 case Stmt::IfStmtClass: {
2784 const auto *IfStatement = cast<IfStmt>(Term);
2785 // Handle if consteval which doesn't have a traditional condition.
2786 if (IfStatement->isConsteval())
2787 return nullptr;
2788 Cond = IfStatement->getCond();
2789 break;
2790 }
2791 case Stmt::ConditionalOperatorClass:
2792 Cond = cast<ConditionalOperator>(Term)->getCond();
2793 break;
2794 case Stmt::BinaryOperatorClass:
2795 // When we encounter a logical operator (&& or ||) as a CFG terminator,
2796 // then the condition is actually its LHS; otherwise, we'd encounter
2797 // the parent, such as if-statement, as a terminator.
2798 const auto *BO = cast<BinaryOperator>(Term);
2799 assert(BO->isLogicalOp() &&
2800 "CFG terminator is not a short-circuit operator!");
2801 Cond = BO->getLHS();
2802 break;
2803 }
2804
2805 Cond = Cond->IgnoreParens();
2806
2807 // However, when we encounter a logical operator as a branch condition,
2808 // then the condition is actually its RHS, because LHS would be
2809 // the condition for the logical operator terminator.
2810 while (const auto *InnerBO = dyn_cast<BinaryOperator>(Cond)) {
2811 if (!InnerBO->isLogicalOp())
2812 break;
2813 Cond = InnerBO->getRHS()->IgnoreParens();
2814 }
2815
2816 assert(Cond);
2817 assert(srcBlk->succ_size() == 2);
2818 const bool TookTrue = *(srcBlk->succ_begin()) == dstBlk;
2819 return VisitTrueTest(Cond, BRC, R, N, TookTrue);
2820}
2821
2825 const ExplodedNode *N, bool TookTrue) {
2826 ProgramStateRef CurrentState = N->getState();
2827 ProgramStateRef PrevState = N->getFirstPred()->getState();
2828 const StackFrame *SF = N->getStackFrame();
2829
2830 // If the constraint information is changed between the current and the
2831 // previous program state we assuming the newly seen constraint information.
2832 // If we cannot evaluate the condition (and the constraints are the same)
2833 // the analyzer has no information about the value and just assuming it.
2834 // FIXME: This logic is not entirely correct, because e.g. in code like
2835 // void f(unsigned arg) {
2836 // if (arg >= 0) {
2837 // // ...
2838 // }
2839 // }
2840 // it will say that the "arg >= 0" check is _assuming_ something new because
2841 // the constraint that "$arg >= 0" is 1 was added to the list of known
2842 // constraints. However, the unsigned value is always >= 0 so semantically
2843 // this is not a "real" assumption.
2844 bool IsAssuming =
2845 !BRC.getStateManager().haveEqualConstraints(CurrentState, PrevState) ||
2846 CurrentState->getSVal(Cond, SF).isUnknownOrUndef();
2847
2848 // These will be modified in code below, but we need to preserve the original
2849 // values in case we want to throw the generic message.
2850 const Expr *CondTmp = Cond;
2851 bool TookTrueTmp = TookTrue;
2852
2853 while (true) {
2854 CondTmp = CondTmp->IgnoreParenCasts();
2855 switch (CondTmp->getStmtClass()) {
2856 default:
2857 break;
2858 case Stmt::BinaryOperatorClass:
2859 if (auto P = VisitTrueTest(Cond, cast<BinaryOperator>(CondTmp),
2860 BRC, R, N, TookTrueTmp, IsAssuming))
2861 return P;
2862 break;
2863 case Stmt::DeclRefExprClass:
2864 if (auto P = VisitTrueTest(Cond, cast<DeclRefExpr>(CondTmp),
2865 BRC, R, N, TookTrueTmp, IsAssuming))
2866 return P;
2867 break;
2868 case Stmt::MemberExprClass:
2869 if (auto P = VisitTrueTest(Cond, cast<MemberExpr>(CondTmp),
2870 BRC, R, N, TookTrueTmp, IsAssuming))
2871 return P;
2872 break;
2873 case Stmt::UnaryOperatorClass: {
2874 const auto *UO = cast<UnaryOperator>(CondTmp);
2875 if (UO->getOpcode() == UO_LNot) {
2876 TookTrueTmp = !TookTrueTmp;
2877 CondTmp = UO->getSubExpr();
2878 continue;
2879 }
2880 break;
2881 }
2882 }
2883 break;
2884 }
2885
2886 // Condition too complex to explain? Just say something so that the user
2887 // knew we've made some path decision at this point.
2888 // If it is too complex and we know the evaluation of the condition do not
2889 // repeat the note from 'BugReporter.cpp'
2890 if (!IsAssuming)
2891 return nullptr;
2892
2894 if (!Loc.isValid() || !Loc.asLocation().isValid())
2895 return nullptr;
2896
2897 return std::make_shared<PathDiagnosticEventPiece>(
2898 Loc, TookTrue ? GenericTrueMessage : GenericFalseMessage);
2899}
2900
2901bool ConditionBRVisitor::patternMatch(const Expr *Ex, const Expr *ParentEx,
2902 raw_ostream &Out, BugReporterContext &BRC,
2903 PathSensitiveBugReport &report,
2904 const ExplodedNode *N,
2905 std::optional<bool> &prunable,
2906 bool IsSameFieldName) {
2907 const Expr *OriginalExpr = Ex;
2908 Ex = Ex->IgnoreParenCasts();
2909
2911 FloatingLiteral>(Ex)) {
2912 // Use heuristics to determine if the expression is a macro
2913 // expanding to a literal and if so, use the macro's name.
2914 SourceLocation BeginLoc = OriginalExpr->getBeginLoc();
2915 SourceLocation EndLoc = OriginalExpr->getEndLoc();
2916 if (BeginLoc.isMacroID() && EndLoc.isMacroID()) {
2917 const SourceManager &SM = BRC.getSourceManager();
2918 const LangOptions &LO = BRC.getASTContext().getLangOpts();
2919 if (Lexer::isAtStartOfMacroExpansion(BeginLoc, SM, LO) &&
2920 Lexer::isAtEndOfMacroExpansion(EndLoc, SM, LO)) {
2921 CharSourceRange R = Lexer::getAsCharRange({BeginLoc, EndLoc}, SM, LO);
2922 Out << Lexer::getSourceText(R, SM, LO);
2923 return false;
2924 }
2925 }
2926 }
2927
2928 if (const auto *DR = dyn_cast<DeclRefExpr>(Ex)) {
2929 const bool quotes = isa<VarDecl>(DR->getDecl());
2930 if (quotes) {
2931 Out << '\'';
2932 const ProgramState *state = N->getState().get();
2933 if (const MemRegion *R =
2934 state->getLValue(cast<VarDecl>(DR->getDecl()), N->getStackFrame())
2935 .getAsRegion()) {
2936 if (report.isInteresting(R))
2937 prunable = false;
2938 else {
2939 const ProgramState *state = N->getState().get();
2940 SVal V = state->getSVal(R);
2941 if (report.isInteresting(V))
2942 prunable = false;
2943 }
2944 }
2945 }
2946 Out << DR->getDecl()->getDeclName().getAsString();
2947 if (quotes)
2948 Out << '\'';
2949 return quotes;
2950 }
2951
2952 if (const auto *IL = dyn_cast<IntegerLiteral>(Ex)) {
2953 QualType OriginalTy = OriginalExpr->getType();
2954 if (OriginalTy->isPointerType()) {
2955 if (IL->getValue() == 0) {
2956 Out << "null";
2957 return false;
2958 }
2959 }
2960 else if (OriginalTy->isObjCObjectPointerType()) {
2961 if (IL->getValue() == 0) {
2962 Out << "nil";
2963 return false;
2964 }
2965 }
2966
2967 Out << IL->getValue();
2968 return false;
2969 }
2970
2971 if (const auto *ME = dyn_cast<MemberExpr>(Ex)) {
2972 if (!IsSameFieldName)
2973 Out << "field '" << ME->getMemberDecl()->getName() << '\'';
2974 else
2975 Out << '\''
2979 nullptr)
2980 << '\'';
2981 }
2982
2983 return false;
2984}
2985
2987 const Expr *Cond, const BinaryOperator *BExpr, BugReporterContext &BRC,
2988 PathSensitiveBugReport &R, const ExplodedNode *N, bool TookTrue,
2989 bool IsAssuming) {
2990 bool shouldInvert = false;
2991 std::optional<bool> shouldPrune;
2992
2993 // Check if the field name of the MemberExprs is ambiguous. Example:
2994 // " 'a.d' is equal to 'h.d' " in 'test/Analysis/null-deref-path-notes.cpp'.
2995 bool IsSameFieldName = false;
2996 const auto *LhsME = dyn_cast<MemberExpr>(BExpr->getLHS()->IgnoreParenCasts());
2997 const auto *RhsME = dyn_cast<MemberExpr>(BExpr->getRHS()->IgnoreParenCasts());
2998
2999 if (LhsME && RhsME)
3000 IsSameFieldName =
3001 LhsME->getMemberDecl()->getName() == RhsME->getMemberDecl()->getName();
3002
3003 SmallString<128> LhsString, RhsString;
3004 {
3005 llvm::raw_svector_ostream OutLHS(LhsString), OutRHS(RhsString);
3006 const bool isVarLHS = patternMatch(BExpr->getLHS(), BExpr, OutLHS, BRC, R,
3007 N, shouldPrune, IsSameFieldName);
3008 const bool isVarRHS = patternMatch(BExpr->getRHS(), BExpr, OutRHS, BRC, R,
3009 N, shouldPrune, IsSameFieldName);
3010
3011 shouldInvert = !isVarLHS && isVarRHS;
3012 }
3013
3014 BinaryOperator::Opcode Op = BExpr->getOpcode();
3015
3017 // For assignment operators, all that we care about is that the LHS
3018 // evaluates to "true" or "false".
3019 return VisitConditionVariable(LhsString, BExpr->getLHS(), BRC, R, N,
3020 TookTrue);
3021 }
3022
3023 // For non-assignment operations, we require that we can understand
3024 // both the LHS and RHS.
3025 if (LhsString.empty() || RhsString.empty() ||
3026 !BinaryOperator::isComparisonOp(Op) || Op == BO_Cmp)
3027 return nullptr;
3028
3029 // Should we invert the strings if the LHS is not a variable name?
3030 SmallString<256> buf;
3031 llvm::raw_svector_ostream Out(buf);
3032 Out << (IsAssuming ? "Assuming " : "")
3033 << (shouldInvert ? RhsString : LhsString) << " is ";
3034
3035 // Do we need to invert the opcode?
3036 if (shouldInvert)
3037 switch (Op) {
3038 default: break;
3039 case BO_LT: Op = BO_GT; break;
3040 case BO_GT: Op = BO_LT; break;
3041 case BO_LE: Op = BO_GE; break;
3042 case BO_GE: Op = BO_LE; break;
3043 }
3044
3045 if (!TookTrue)
3046 switch (Op) {
3047 case BO_EQ: Op = BO_NE; break;
3048 case BO_NE: Op = BO_EQ; break;
3049 case BO_LT: Op = BO_GE; break;
3050 case BO_GT: Op = BO_LE; break;
3051 case BO_LE: Op = BO_GT; break;
3052 case BO_GE: Op = BO_LT; break;
3053 default:
3054 return nullptr;
3055 }
3056
3057 switch (Op) {
3058 case BO_EQ:
3059 Out << "equal to ";
3060 break;
3061 case BO_NE:
3062 Out << "not equal to ";
3063 break;
3064 default:
3065 Out << BinaryOperator::getOpcodeStr(Op) << ' ';
3066 break;
3067 }
3068
3069 Out << (shouldInvert ? LhsString : RhsString);
3070 const StackFrame *SF = N->getStackFrame();
3071 const SourceManager &SM = BRC.getSourceManager();
3072
3073 if (isVarAnInterestingCondition(BExpr->getLHS(), N, &R) ||
3074 isVarAnInterestingCondition(BExpr->getRHS(), N, &R))
3076
3077 // Convert 'field ...' to 'Field ...' if it is a MemberExpr.
3078 std::string Message = std::string(Out.str());
3079 Message[0] = toupper(Message[0]);
3080
3081 // If we know the value create a pop-up note to the value part of 'BExpr'.
3082 if (!IsAssuming) {
3084 if (!shouldInvert) {
3085 if (LhsME && LhsME->getMemberLoc().isValid())
3086 Loc = PathDiagnosticLocation(LhsME->getMemberLoc(), SM);
3087 else
3088 Loc = PathDiagnosticLocation(BExpr->getLHS(), SM, SF);
3089 } else {
3090 if (RhsME && RhsME->getMemberLoc().isValid())
3091 Loc = PathDiagnosticLocation(RhsME->getMemberLoc(), SM);
3092 else
3093 Loc = PathDiagnosticLocation(BExpr->getRHS(), SM, SF);
3094 }
3095
3096 return std::make_shared<PathDiagnosticPopUpPiece>(Loc, Message);
3097 }
3098
3100 auto event = std::make_shared<PathDiagnosticEventPiece>(Loc, Message);
3101 if (shouldPrune)
3102 event->setPrunable(*shouldPrune);
3103 return event;
3104}
3105
3107 StringRef LhsString, const Expr *CondVarExpr, BugReporterContext &BRC,
3108 PathSensitiveBugReport &report, const ExplodedNode *N, bool TookTrue) {
3109 // FIXME: If there's already a constraint tracker for this variable,
3110 // we shouldn't emit anything here (c.f. the double note in
3111 // test/Analysis/inlining/path-notes.c)
3112 SmallString<256> buf;
3113 llvm::raw_svector_ostream Out(buf);
3114 Out << "Assuming " << LhsString << " is ";
3115
3116 if (!printValue(CondVarExpr, Out, N, TookTrue, /*IsAssuming=*/true))
3117 return nullptr;
3118
3119 PathDiagnosticLocation Loc(CondVarExpr, BRC.getSourceManager(),
3120 N->getStackFrame());
3121
3122 if (isVarAnInterestingCondition(CondVarExpr, N, &report))
3124
3125 auto event = std::make_shared<PathDiagnosticEventPiece>(Loc, Out.str());
3126
3127 if (isInterestingExpr(CondVarExpr, N, &report))
3128 event->setPrunable(false);
3129
3130 return event;
3131}
3132
3134 const Expr *Cond, const DeclRefExpr *DRE, BugReporterContext &BRC,
3135 PathSensitiveBugReport &report, const ExplodedNode *N, bool TookTrue,
3136 bool IsAssuming) {
3137 const auto *VD = dyn_cast<VarDecl>(DRE->getDecl());
3138 if (!VD)
3139 return nullptr;
3140
3141 SmallString<256> Buf;
3142 llvm::raw_svector_ostream Out(Buf);
3143
3144 Out << (IsAssuming ? "Assuming '" : "'") << VD->getDeclName() << "' is ";
3145
3146 if (!printValue(DRE, Out, N, TookTrue, IsAssuming))
3147 return nullptr;
3148
3149 const StackFrame *SF = N->getStackFrame();
3150
3151 if (isVarAnInterestingCondition(DRE, N, &report))
3153
3154 // If we know the value create a pop-up note to the 'DRE'.
3155 if (!IsAssuming) {
3157 return std::make_shared<PathDiagnosticPopUpPiece>(Loc, Out.str());
3158 }
3159
3161 auto event = std::make_shared<PathDiagnosticEventPiece>(Loc, Out.str());
3162
3163 if (isInterestingExpr(DRE, N, &report))
3164 event->setPrunable(false);
3165
3166 return std::move(event);
3167}
3168
3170 const Expr *Cond, const MemberExpr *ME, BugReporterContext &BRC,
3171 PathSensitiveBugReport &report, const ExplodedNode *N, bool TookTrue,
3172 bool IsAssuming) {
3173 SmallString<256> Buf;
3174 llvm::raw_svector_ostream Out(Buf);
3175
3176 Out << (IsAssuming ? "Assuming field '" : "Field '")
3177 << ME->getMemberDecl()->getName() << "' is ";
3178
3179 if (!printValue(ME, Out, N, TookTrue, IsAssuming))
3180 return nullptr;
3181
3183
3184 // If we know the value create a pop-up note to the member of the MemberExpr.
3185 if (!IsAssuming && ME->getMemberLoc().isValid())
3187 else
3189 N->getStackFrame());
3190
3191 if (!Loc.isValid() || !Loc.asLocation().isValid())
3192 return nullptr;
3193
3194 if (isVarAnInterestingCondition(ME, N, &report))
3196
3197 // If we know the value create a pop-up note.
3198 if (!IsAssuming)
3199 return std::make_shared<PathDiagnosticPopUpPiece>(Loc, Out.str());
3200
3201 auto event = std::make_shared<PathDiagnosticEventPiece>(Loc, Out.str());
3202 if (isInterestingExpr(ME, N, &report))
3203 event->setPrunable(false);
3204 return event;
3205}
3206
3207bool ConditionBRVisitor::printValue(const Expr *CondVarExpr, raw_ostream &Out,
3208 const ExplodedNode *N, bool TookTrue,
3209 bool IsAssuming) {
3210 QualType Ty = CondVarExpr->getType();
3211
3212 if (Ty->isPointerType()) {
3213 Out << (TookTrue ? "non-null" : "null");
3214 return true;
3215 }
3216
3217 if (Ty->isObjCObjectPointerType()) {
3218 Out << (TookTrue ? "non-nil" : "nil");
3219 return true;
3220 }
3221
3222 if (!Ty->isIntegralOrEnumerationType())
3223 return false;
3224
3225 std::optional<const llvm::APSInt *> IntValue;
3226 if (!IsAssuming)
3227 IntValue = getConcreteIntegerValue(CondVarExpr, N);
3228
3229 if (IsAssuming || !IntValue) {
3230 if (Ty->isBooleanType())
3231 Out << (TookTrue ? "true" : "false");
3232 else
3233 Out << (TookTrue ? "not equal to 0" : "0");
3234 } else {
3235 if (Ty->isBooleanType())
3236 Out << ((*IntValue)->getBoolValue() ? "true" : "false");
3237 else
3238 Out << **IntValue;
3239 }
3240
3241 return true;
3242}
3243
3245 const PathDiagnosticPiece *Piece) {
3246 return Piece->getString() == GenericTrueMessage ||
3247 Piece->getString() == GenericFalseMessage;
3248}
3249
3250//===----------------------------------------------------------------------===//
3251// Implementation of LikelyFalsePositiveSuppressionBRVisitor.
3252//===----------------------------------------------------------------------===//
3253
3255 BugReporterContext &BRC, const ExplodedNode *N,
3257 // Here we suppress false positives coming from system headers. This list is
3258 // based on known issues.
3259 const AnalyzerOptions &Options = BRC.getAnalyzerOptions();
3260 const Decl *D = N->getStackFrame()->getDecl();
3261
3263 // Skip reports within the 'std' namespace. Although these can sometimes be
3264 // the user's fault, we currently don't report them very well, and
3265 // Note that this will not help for any other data structure libraries, like
3266 // TR1, Boost, or llvm/ADT.
3267 if (Options.ShouldSuppressFromCXXStandardLibrary) {
3268 BR.markInvalid(getTag(), nullptr);
3269 return;
3270 } else {
3271 // If the complete 'std' suppression is not enabled, suppress reports
3272 // from the 'std' namespace that are known to produce false positives.
3273
3274 // The analyzer issues a false use-after-free when std::list::pop_front
3275 // or std::list::pop_back are called multiple times because we cannot
3276 // reason about the internal invariants of the data structure.
3277 if (const auto *MD = dyn_cast<CXXMethodDecl>(D)) {
3278 const CXXRecordDecl *CD = MD->getParent();
3279 if (CD->getName() == "list") {
3280 BR.markInvalid(getTag(), nullptr);
3281 return;
3282 }
3283 }
3284
3285 // The analyzer issues a false positive when the constructor of
3286 // std::__independent_bits_engine from algorithms is used.
3287 if (const auto *MD = dyn_cast<CXXConstructorDecl>(D)) {
3288 const CXXRecordDecl *CD = MD->getParent();
3289 if (CD->getName() == "__independent_bits_engine") {
3290 BR.markInvalid(getTag(), nullptr);
3291 return;
3292 }
3293 }
3294
3295 for (const auto *SF = N->getStackFrame(); SF; SF = SF->getParent()) {
3296 const auto *MD = dyn_cast<CXXMethodDecl>(SF->getDecl());
3297 if (!MD)
3298 continue;
3299
3300 const CXXRecordDecl *CD = MD->getParent();
3301 // The analyzer issues a false positive on
3302 // std::basic_string<uint8_t> v; v.push_back(1);
3303 // and
3304 // std::u16string s; s += u'a';
3305 // because we cannot reason about the internal invariants of the
3306 // data structure.
3307 if (CD->getName() == "basic_string") {
3308 BR.markInvalid(getTag(), nullptr);
3309 return;
3310 }
3311
3312 // The analyzer issues a false positive on
3313 // std::shared_ptr<int> p(new int(1)); p = nullptr;
3314 // because it does not reason properly about temporary destructors.
3315 if (CD->getName() == "shared_ptr") {
3316 BR.markInvalid(getTag(), nullptr);
3317 return;
3318 }
3319 }
3320 }
3321 }
3322
3323 // Skip reports within the sys/queue.h macros as we do not have the ability to
3324 // reason about data structure shapes.
3325 const SourceManager &SM = BRC.getSourceManager();
3327 while (Loc.isMacroID()) {
3328 Loc = Loc.getSpellingLoc();
3329 if (SM.getFilename(Loc).ends_with("sys/queue.h")) {
3330 BR.markInvalid(getTag(), nullptr);
3331 return;
3332 }
3333 }
3334}
3335
3336//===----------------------------------------------------------------------===//
3337// Implementation of UndefOrNullArgVisitor.
3338//===----------------------------------------------------------------------===//
3339
3343 ProgramStateRef State = N->getState();
3344 ProgramPoint ProgLoc = N->getLocation();
3345
3346 // We are only interested in visiting CallEnter nodes.
3347 std::optional<CallEnter> CEnter = ProgLoc.getAs<CallEnter>();
3348 if (!CEnter)
3349 return nullptr;
3350
3351 // Check if one of the arguments is the region the visitor is tracking.
3353 CallEventRef<> Call = CEMgr.getCaller(CEnter->getCalleeStackFrame(), State);
3354 unsigned Idx = 0;
3355 ArrayRef<ParmVarDecl *> parms = Call->parameters();
3356
3357 for (const auto ParamDecl : parms) {
3358 const MemRegion *ArgReg = Call->getArgSVal(Idx).getAsRegion();
3359 ++Idx;
3360
3361 // Are we tracking the argument or its subregion?
3362 if ( !ArgReg || !R->isSubRegionOf(ArgReg->StripCasts()))
3363 continue;
3364
3365 // Check the function parameter type.
3366 assert(ParamDecl && "Formal parameter has no decl?");
3367 QualType T = ParamDecl->getType();
3368
3369 if (!(T->isAnyPointerType() || T->isReferenceType())) {
3370 // Function can only change the value passed in by address.
3371 continue;
3372 }
3373
3374 // If it is a const pointer value, the function does not intend to
3375 // change the value.
3376 if (T->getPointeeType().isConstQualified())
3377 continue;
3378
3379 // Mark the call site (StackFrame) as interesting if the value of the
3380 // argument is undefined or '0'/'NULL'.
3381 SVal BoundVal = State->getSVal(R);
3382 if (BoundVal.isUndef() || BoundVal.isZeroConstant()) {
3383 BR.markInteresting(CEnter->getCalleeStackFrame());
3384 return nullptr;
3385 }
3386 }
3387 return nullptr;
3388}
3389
3390//===----------------------------------------------------------------------===//
3391// Implementation of TagVisitor.
3392//===----------------------------------------------------------------------===//
3393
3394int NoteTag::Kind = 0;
3395
3396void TagVisitor::Profile(llvm::FoldingSetNodeID &ID) const {
3397 static int Tag = 0;
3398 ID.AddPointer(&Tag);
3399}
3400
3402 BugReporterContext &BRC,
3404 ProgramPoint PP = N->getLocation();
3405 const NoteTag *T = dyn_cast_or_null<NoteTag>(PP.getTag());
3406 if (!T)
3407 return nullptr;
3408
3409 if (std::optional<std::string> Msg = T->generateMessage(BRC, R)) {
3412 auto Piece = std::make_shared<PathDiagnosticEventPiece>(Loc, *Msg);
3413 Piece->setPrunable(T->isPrunable());
3414 return Piece;
3415 }
3416
3417 return nullptr;
3418}
Defines the clang::ASTContext interface.
#define V(N, I)
This file defines AnalysisDeclContext, a class that manages the analysis context data for context sen...
static bool isInterestingExpr(const Expr *E, const ExplodedNode *N, const PathSensitiveBugReport *B)
static const ExplodedNode * findNodeForExpression(const ExplodedNode *N, const Expr *Inner)
Find the ExplodedNode where the lvalue (the value of 'Ex') was computed.
static void showBRParamDiagnostics(llvm::raw_svector_ostream &OS, StoreInfo SI)
Display diagnostics for passing bad region as a parameter.
static const Expr * peelOffPointerArithmetic(const BinaryOperator *B)
static const Expr * tryExtractInitializerFromList(const InitListExpr *ILE, const MemRegion *R)
static bool wasRegionOfInterestModifiedAt(const SubRegion *RegionOfInterest, const ExplodedNode *N, SVal ValueAfter)
static llvm::StringLiteral WillBeUsedForACondition
static bool isFunctionMacroExpansion(SourceLocation Loc, const SourceManager &SM)
static std::shared_ptr< PathDiagnosticEventPiece > constructDebugPieceForTrackedCondition(const Expr *Cond, const ExplodedNode *N, BugReporterContext &BRC)
static const MemRegion * getLocationRegionIfReference(const Expr *E, const ExplodedNode *N, bool LookingForReference=true)
static bool hasVisibleUpdate(const ExplodedNode *LeftNode, SVal LeftVal, const ExplodedNode *RightNode, SVal RightVal)
Comparing internal representations of symbolic values (via SVal::operator==()) is a valid way to chec...
static bool potentiallyWritesIntoIvar(const Decl *Parent, const ObjCIvarDecl *Ivar)
static std::optional< const llvm::APSInt * > getConcreteIntegerValue(const Expr *CondVarExpr, const ExplodedNode *N)
static bool isVarAnInterestingCondition(const Expr *CondVarExpr, const ExplodedNode *N, const PathSensitiveBugReport *B)
static void showBRDefaultDiagnostics(llvm::raw_svector_ostream &OS, StoreInfo SI)
Show default diagnostics for storing bad region.
static std::optional< SVal > getSValForVar(const Expr *CondVarExpr, const ExplodedNode *N)
static const Expr * peelOffOuterExpr(const Expr *Ex, const ExplodedNode *N)
static const VarDecl * getVarDeclForExpression(const Expr *E)
static bool isTrivialCopyOrMoveCtor(const CXXConstructExpr *CE)
static StringRef getMacroName(SourceLocation Loc, BugReporterContext &BRC)
static bool isObjCPointer(const MemRegion *R)
static bool isAssertlikeBlock(const CFGBlock *B, ASTContext &Context)
static bool isInitializationOfVar(const ExplodedNode *N, const VarRegion *VR)
Returns true if N represents the DeclStmt declaring and initializing VR.
static const ExplodedNode * getMatchingCallExitEnd(const ExplodedNode *N)
static void showBRDiagnostics(llvm::raw_svector_ostream &OS, StoreInfo SI)
Show diagnostics for initializing or declaring a region R with a bad value.
Defines the C++ Decl subclasses, other than those for templates (found in DeclTemplate....
Defines the clang::Expr interface and subclasses for C++ expressions.
Defines the clang::IdentifierInfo, clang::IdentifierTable, and clang::Selector interfaces.
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.
#define SM(sm)
Defines the clang::SourceLocation class and associated facilities.
Defines the SourceManager interface.
C Language Family Type Representation.
static bool isPointerToConst(const QualType &QT)
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition ASTContext.h:223
const LangOptions & getLangOpts() const
Definition ASTContext.h:959
static bool isInStdNamespace(const Decl *D)
Stores options for the analyzer from the command line.
AnalysisDiagClients AnalysisDiagOpt
A builtin binary operation expression such as "x + y" or "x <= y".
Definition Expr.h:4044
Expr * getLHS() const
Definition Expr.h:4094
static bool isComparisonOp(Opcode Opc)
Definition Expr.h:4144
StringRef getOpcodeStr() const
Definition Expr.h:4110
Expr * getRHS() const
Definition Expr.h:4096
static bool isAdditiveOp(Opcode Opc)
Definition Expr.h:4130
static bool isAssignmentOp(Opcode Opc)
Definition Expr.h:4180
Opcode getOpcode() const
Definition Expr.h:4089
BinaryOperatorKind Opcode
Definition Expr.h:4049
Represents a single basic block in a source-level CFG.
Definition CFG.h:652
bool isInevitablySinking() const
Returns true if the block would eventually end with a sink (a noreturn node).
Definition CFG.cpp:6455
succ_iterator succ_begin()
Definition CFG.h:1037
Stmt * getTerminatorStmt()
Definition CFG.h:1134
const Stmt * getTerminatorCondition(bool StripParens=true) const
Definition CFG.cpp:6520
const Expr * getLastCondition() const
Definition CFG.cpp:6492
unsigned succ_size() const
Definition CFG.h:1055
const CFGBlock * getBlock(const Stmt *S) const
Returns the CFGBlock the specified Stmt* appears in.
unsigned size() const
Return the total number of CFGBlocks within the CFG This is simply a renaming of the getNumBlockIDs()...
Definition CFG.h:1469
bool isLinear() const
Returns true if the CFG has no branches.
Definition CFG.cpp:5465
A boolean literal, per ([C++ lex.bool] Boolean literals).
Definition ExprCXX.h:727
Represents a call to a C++ constructor.
Definition ExprCXX.h:1552
CXXConstructorDecl * getConstructor() const
Get the constructor that this expression will (ultimately) call.
Definition ExprCXX.h:1615
bool isCopyOrMoveConstructor(unsigned &TypeQuals) const
Determine whether this is a copy or move constructor.
Definition DeclCXX.cpp:3067
Represents a C++ struct/union/class.
Definition DeclCXX.h:258
Represents a point when we begin processing an inlined call.
Represents a point when we start the call exit sequence (for inlined call).
Represents a point when we finish the call exit sequence (for inlined call).
Represents a byte-granular source range.
static CharSourceRange getTokenRange(SourceRange R)
DeclContext * getParent()
getParent - Returns the containing DeclContext.
Definition DeclBase.h:2122
A reference to a declared variable, function, enum, etc.
Definition Expr.h:1276
ValueDecl * getDecl()
Definition Expr.h:1344
DeclStmt - Adaptor class for mixing declarations with statements and expressions.
Definition Stmt.h:1641
const Decl * getSingleDecl() const
Definition Stmt.h:1656
Decl - This represents one declaration (or definition), e.g.
Definition DeclBase.h:86
ASTContext & getASTContext() const LLVM_READONLY
Definition DeclBase.cpp:547
virtual Stmt * getBody() const
getBody - If this Decl represents a declaration for a body of code, such as a function or method defi...
Definition DeclBase.h:1100
virtual bool hasBody() const
Returns true if this Decl represents a declaration for a body of code, such as a function or method d...
Definition DeclBase.h:1106
bool isLocalExternDecl() const
Determine whether this is a block-scope declaration with linkage.
Definition DeclBase.h:1182
This represents one expression.
Definition Expr.h:112
bool isGLValue() const
Definition Expr.h:287
Expr * IgnoreParenCasts() LLVM_READONLY
Skip past any parentheses and casts which might surround this expression until reaching a fixed point...
Definition Expr.cpp:3104
bool isPRValue() const
Definition Expr.h:285
Expr * IgnoreImpCasts() LLVM_READONLY
Skip past any implicit casts which might surround this expression until reaching a fixed point.
Definition Expr.cpp:3079
QualType getType() const
Definition Expr.h:144
A SourceLocation and its associated SourceManager.
GNUNullExpr - Implements the GNU __null extension, which is a name for a null pointer constant that h...
Definition Expr.h:4929
Describes an C or C++ initializer list.
Definition Expr.h:5305
unsigned getNumInits() const
Definition Expr.h:5338
const Expr * getInit(unsigned Init) const
Definition Expr.h:5360
Keeps track of the various options that can be enabled, which controls the dialect of C or C++ that i...
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:1074
static StringRef getImmediateMacroName(SourceLocation Loc, const SourceManager &SM, const LangOptions &LangOpts)
Retrieve the name of the immediate macro expansion.
Definition Lexer.cpp:1110
static CharSourceRange getAsCharRange(SourceRange Range, const SourceManager &SM, const LangOptions &LangOpts)
Given a token range, produce a corresponding CharSourceRange that is not a token range.
Definition Lexer.h:438
static bool isAtStartOfMacroExpansion(SourceLocation loc, const SourceManager &SM, const LangOptions &LangOpts, SourceLocation *MacroBegin=nullptr)
Returns true if the given MacroID location points at the first token of the macro expansion.
Definition Lexer.cpp:911
static bool isAtEndOfMacroExpansion(SourceLocation loc, const SourceManager &SM, const LangOptions &LangOpts, SourceLocation *MacroEnd=nullptr)
Returns true if the given MacroID location points at the last token of the macro expansion.
Definition Lexer.cpp:933
MemberExpr - [C99 6.5.2.3] Structure and Union Members.
Definition Expr.h:3370
SourceLocation getMemberLoc() const
getMemberLoc - Return the location of the "member", in X->F, it is the location of 'F'.
Definition Expr.h:3559
ValueDecl * getMemberDecl() const
Retrieve the member declaration to which this expression refers.
Definition Expr.h:3453
StringRef getName() const
Get the name of identifier for this declaration as a StringRef.
Definition Decl.h:301
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:317
ObjCBoolLiteralExpr - Objective-C Boolean Literal.
Definition ExprObjC.h:119
ObjCIvarDecl - Represents an ObjC instance variable.
Definition DeclObjC.h:1952
ObjCIvarRefExpr - A reference to an ObjC instance variable.
Definition ExprObjC.h:580
Represents a program point after a store evaluation.
ProgramPoints can be "tagged" as representing points specific to a given analysis entity.
const ProgramPointTag * getTag() const
const StackFrame * getStackFrame() 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:937
bool isNull() const
Return true if this QualType doesn't point to a type yet.
Definition TypeBase.h:1004
QualType getCanonicalType() const
Definition TypeBase.h:8499
bool isConstQualified() const
Determine whether this type is const-qualified.
Definition TypeBase.h:8520
field_range fields() const
Definition Decl.h:4550
Encodes a location in the source.
bool isValid() const
Return true if this is a valid SourceLocation object.
This class handles loading and caching of source files into memory.
A trivial tuple used to represent a source range.
Each ExpansionInfo encodes the expansion location - where the token was ultimately expanded,...
This is a discriminated union of FileInfo and ExpansionInfo.
const ExpansionInfo & getExpansion() const
It represents a stack frame of the call stack.
bool isParentOf(const StackFrame *SF) const
LLVM_ATTRIBUTE_RETURNS_NONNULL AnalysisDeclContext * getAnalysisDeclContext() const
const Expr * getCallSite() const
const Decl * getDecl() const
const StackFrame * getParent() const
It might return null.
Stmt - This represents one statement.
Definition Stmt.h:86
SourceLocation getEndLoc() const LLVM_READONLY
Definition Stmt.cpp:367
StmtClass getStmtClass() const
Definition Stmt.h:1503
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
bool isVoidType() const
Definition TypeBase.h:9050
bool isBooleanType() const
Definition TypeBase.h:9187
RecordDecl * getAsRecordDecl() const
Retrieves the RecordDecl this type refers to.
Definition Type.h:41
bool isPointerType() const
Definition TypeBase.h:8684
bool isReferenceType() const
Definition TypeBase.h:8708
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
Definition Type.cpp:789
bool isIntegralOrEnumerationType() const
Determine whether this type is an integral or enumeration type.
Definition TypeBase.h:9172
bool isObjCObjectPointerType() const
Definition TypeBase.h:8863
const T * getAs() const
Member-template getAs<specific type>'.
Definition TypeBase.h:9277
Represent the declaration of a variable (in which case it is an lvalue) a function (in which case it ...
Definition Decl.h:712
QualType getType() const
Definition Decl.h:723
Represents a variable declaration or definition.
Definition Decl.h:924
bool hasGlobalStorage() const
Returns true for all variables that do not have local storage.
Definition Decl.h:1239
bool isStaticLocal() const
Returns true if a variable with function scope is a static local variable.
Definition Decl.h:1206
const Expr * getInit() const
Definition Decl.h:1381
bool hasLocalStorage() const
Returns true if a variable with function scope is a non-static local variable.
Definition Decl.h:1182
Maps string IDs to AST nodes matched by parts of a matcher.
A safe wrapper around APSInt objects allocated and owned by BasicValueFactory.
Definition APSIntPtr.h:19
StringRef getDescription() const
A verbose warning message that is appropriate for displaying next to the source code that introduces ...
ASTContext & getASTContext() const
ProgramStateManager & getStateManager() const
const SourceManager & getSourceManager() const
const AnalyzerOptions & getAnalyzerOptions() const
BugReporterVisitors are used to add custom diagnostics along a path.
static PathDiagnosticPieceRef getDefaultEndPath(const BugReporterContext &BRC, const ExplodedNode *N, const PathSensitiveBugReport &BR)
Generates the default final diagnostic piece.
virtual PathDiagnosticPieceRef getEndPath(BugReporterContext &BRC, const ExplodedNode *N, PathSensitiveBugReport &BR)
Provide custom definition for the final diagnostic piece on the path - the piece, which is displayed ...
virtual void finalizeVisitor(BugReporterContext &BRC, const ExplodedNode *EndPathNode, PathSensitiveBugReport &BR)
Last function called on the visitor, no further calls to VisitNode would follow.
Represents a call to a C++ constructor.
Definition CallEvent.h:990
Manages the lifetime of CallEvent objects.
Definition CallEvent.h:1363
CallEventRef getCaller(const StackFrame *CalleeSF, ProgramStateRef State)
Gets an outside caller given a callee context.
Represents an abstract call to a function or method along a particular path.
Definition CallEvent.h:152
static bool isCallStmt(const Stmt *S)
Returns true if this is a statement is a function or method call of some kind.
PathDiagnosticPieceRef VisitTerminator(const Stmt *Term, const ExplodedNode *N, const CFGBlock *SrcBlk, const CFGBlock *DstBlk, PathSensitiveBugReport &R, BugReporterContext &BRC)
bool printValue(const Expr *CondVarExpr, raw_ostream &Out, const ExplodedNode *N, bool TookTrue, bool IsAssuming)
Tries to print the value of the given expression.
PathDiagnosticPieceRef VisitNode(const ExplodedNode *N, BugReporterContext &BRC, PathSensitiveBugReport &BR) override
Return a diagnostic piece which should be associated with the given node.
bool patternMatch(const Expr *Ex, const Expr *ParentEx, raw_ostream &Out, BugReporterContext &BRC, PathSensitiveBugReport &R, const ExplodedNode *N, std::optional< bool > &prunable, bool IsSameFieldName)
static bool isPieceMessageGeneric(const PathDiagnosticPiece *Piece)
PathDiagnosticPieceRef VisitConditionVariable(StringRef LhsString, const Expr *CondVarExpr, BugReporterContext &BRC, PathSensitiveBugReport &R, const ExplodedNode *N, bool TookTrue)
PathDiagnosticPieceRef VisitTrueTest(const Expr *Cond, BugReporterContext &BRC, PathSensitiveBugReport &R, const ExplodedNode *N, bool TookTrue)
static const char * getTag()
Return the tag associated with this visitor.
PathDiagnosticPieceRef VisitNodeImpl(const ExplodedNode *N, BugReporterContext &BRC, PathSensitiveBugReport &BR)
bool isConstrainedTrue() const
Return true if the constraint is perfectly constrained to 'true'.
bool isValid() const =delete
static bool isInterestingLValueExpr(const Expr *Ex)
Returns true if nodes for the given expression kind are always kept around.
const CFGBlock * getCFGBlock() const
const ProgramStateRef & getState() const
SVal getSVal(const Expr *E) const
Get the value of an arbitrary expression at this node.
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.
ExplodedNode * getFirstSucc()
std::optional< T > getLocationAs() const &
ExplodedNode * getFirstPred()
unsigned succ_size() const
const StackFrame * getStackFrame() const
static std::pair< const ProgramPointTag *, const ProgramPointTag * > getEagerlyAssumeBifurcationTags()
LLVM_ATTRIBUTE_RETURNS_NONNULL const FieldDecl * getDecl() const override
Definition MemRegion.h:1156
void finalizeVisitor(BugReporterContext &BRC, const ExplodedNode *N, PathSensitiveBugReport &BR) override
Last function called on the visitor, no further calls to VisitNode would follow.
MemRegion - The root abstract class for all memory regions.
Definition MemRegion.h:97
const MemSpace * getMemorySpaceAs(ProgramStateRef State) const
Definition MemRegion.h:142
LLVM_ATTRIBUTE_RETURNS_NONNULL const MemRegion * StripCasts(bool StripBaseAndDerivedCasts=true) const
virtual bool isSubRegionOf(const MemRegion *R) const
Check if the region is a subregion of the given region.
virtual void printPretty(raw_ostream &os) const
Print the region for use in diagnostics.
virtual bool canPrintPretty() const
Returns true if this region can be printed in a user-friendly way.
PathDiagnosticPieceRef VisitNode(const ExplodedNode *N, BugReporterContext &BRC, PathSensitiveBugReport &BR) override
Return a diagnostic piece which should be associated with the given node.
static const Expr * getNilReceiver(const Stmt *S, const ExplodedNode *N)
If the statement is a message send expression with nil receiver, returns the receiver expression.
virtual bool wasModifiedBeforeCallExit(const ExplodedNode *CurrN, const ExplodedNode *CallExitBeginN)
virtual PathDiagnosticPieceRef maybeEmitNoteForObjCSelf(PathSensitiveBugReport &R, const ObjCMethodCall &Call, const ExplodedNode *N)=0
Consume the information on the non-modifying stack frame in order to either emit a note or not.
virtual PathDiagnosticPieceRef maybeEmitNoteForCXXThis(PathSensitiveBugReport &R, const CXXConstructorCall &Call, const ExplodedNode *N)=0
Consume the information on the non-modifying stack frame in order to either emit a note or not.
virtual bool wasModifiedInFunction(const ExplodedNode *CallEnterN, const ExplodedNode *CallExitEndN)
PathDiagnosticPieceRef VisitNode(const ExplodedNode *N, BugReporterContext &BR, PathSensitiveBugReport &R) final
Return a diagnostic piece which should be associated with the given node.
virtual PathDiagnosticPieceRef maybeEmitNoteForParameters(PathSensitiveBugReport &R, const CallEvent &Call, const ExplodedNode *N)=0
Consume the information on the non-modifying stack frame in order to either emit a note or not.
The tag upon which the TagVisitor reacts.
Represents any expression that calls an Objective-C method.
Definition CallEvent.h:1251
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.
PathDiagnosticLocation getLocation() const override
The primary location of the bug report that points at the undesirable behavior in the code.
ArrayRef< SourceRange > getRanges() const override
Get the SourceRanges associated with the report.
const ExplodedNode * getErrorNode() const
bool addTrackedCondition(const ExplodedNode *Cond)
Notes that the condition of the CFGBlock associated with Cond is being tracked.
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...
void addVisitor(std::unique_ptr< BugReporterVisitor > visitor)
Add custom or predefined bug report visitors to this report.
std::optional< bugreporter::TrackingKind > getInterestingnessKind(SymbolRef sym) const
bool isInteresting(SymbolRef sym) const
CallEventManager & getCallEventManager()
bool haveEqualConstraints(ProgramStateRef S1, ProgramStateRef S2) const
void iterBindings(ProgramStateRef state, StoreManager::BindingsHandler &F)
ProgramState - This class encapsulates:
Loc getLValue(const CXXBaseSpecifier &BaseSpec, const SubRegion *Super) const
Get the lvalue for a base class object reference.
SVal getSVal(const Expr *E, const StackFrame *SF) const
Returns the SVal bound to the expression E in the state's environment.
A Range represents the closed range [from, to].
ConditionTruthVal areEqual(ProgramStateRef state, SVal lhs, SVal rhs)
SVal - This represents a symbolic expression, which can be either an L-value or an R-value.
Definition SVals.h:56
bool isUndef() const
Definition SVals.h:107
bool isZeroConstant() const
Definition SVals.cpp:257
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:87
const MemRegion * getAsRegion() const
Definition SVals.cpp:119
bool isUnknown() const
Definition SVals.h:105
SubRegion - A region that subsets another larger region.
Definition MemRegion.h:473
LLVM_ATTRIBUTE_RETURNS_NONNULL const MemRegion * getSuperRegion() const
Definition MemRegion.h:486
bool isSubRegionOf(const MemRegion *R) const override
Check if the region is a subregion of the given region.
PathDiagnosticPieceRef VisitNode(const ExplodedNode *Succ, BugReporterContext &BRC, PathSensitiveBugReport &BR) override
Return a diagnostic piece which should be associated with the given node.
SuppressInlineDefensiveChecksVisitor(DefinedSVal Val, const ExplodedNode *N)
static const char * getTag()
Return the tag associated with this visitor.
void Profile(llvm::FoldingSetNodeID &ID) const override
void Profile(llvm::FoldingSetNodeID &ID) const override
PathDiagnosticPieceRef VisitNode(const ExplodedNode *N, BugReporterContext &BRC, PathSensitiveBugReport &R) override
Return a diagnostic piece which should be associated with the given node.
void Profile(llvm::FoldingSetNodeID &ID) const override
static const char * getTag()
Return the tag associated with this visitor.
PathDiagnosticPieceRef VisitNode(const ExplodedNode *N, BugReporterContext &BRC, PathSensitiveBugReport &BR) override
Return a diagnostic piece which should be associated with the given node.
TypedRegion - An abstract class representing regions that are typed.
Definition MemRegion.h:538
PathDiagnosticPieceRef VisitNode(const ExplodedNode *N, BugReporterContext &BRC, PathSensitiveBugReport &BR) override
Return a diagnostic piece which should be associated with the given node.
const VarDecl * getDecl() const override=0
Handles expressions during the tracking.
Handles stores during the tracking.
PathDiagnosticPieceRef constructNote(StoreInfo SI, BugReporterContext &BRC, StringRef NodeText)
void addLowPriorityHandler(ExpressionHandlerPtr SH)
Add custom expression handler with the lowest priority.
static TrackerRef create(PathSensitiveBugReport &Report)
virtual PathDiagnosticPieceRef handle(StoreInfo SI, BugReporterContext &BRC, TrackingOptions Opts)
Handle the store operation and produce the note.
void addHighPriorityHandler(ExpressionHandlerPtr SH)
Add custom expression handler with the highest priority.
Tracker(PathSensitiveBugReport &Report)
virtual Result track(const Expr *E, const ExplodedNode *N, TrackingOptions Opts={})
Track expression value back to its point of origin.
Visitor that tracks expressions and values.
Value representing integer constant.
Definition SVals.h:300
While nonloc::CompoundVal covers a few simple use cases, nonloc::LazyCompoundVal is a more performant...
Definition SVals.h:389
LLVM_ATTRIBUTE_RETURNS_NONNULL const TypedValueRegion * getRegion() const
This function itself is immaterial.
Definition SVals.cpp:193
const internal::VariadicDynCastAllOfMatcher< Stmt, ObjCIvarRefExpr > objcIvarRefExpr
Matches a reference to an ObjCIvar.
const internal::ArgumentAdaptingMatcherFunc< internal::HasDescendantMatcher > hasDescendant
Matches AST nodes that have descendant AST nodes that match the provided matcher.
SmallVector< BoundNodes, 1 > match(MatcherT Matcher, const NodeT &Node, ASTContext &Context)
Returns the results of matching Matcher on Node.
internal::Matcher< Stmt > StatementMatcher
const internal::VariadicDynCastAllOfMatcher< Stmt, BinaryOperator > binaryOperator
Matches binary operator expressions.
internal::PolymorphicMatcher< internal::HasDeclarationMatcher, void(internal::HasDeclarationSupportedTypes), internal::Matcher< Decl > > hasDeclaration(const internal::Matcher< Decl > &InnerMatcher)
Matches a node if the declaration associated with that node matches the given matcher.
const internal::VariadicAllOfMatcher< Stmt > stmt
Matches statements.
llvm::IntrusiveRefCntPtr< Tracker > TrackerRef
const Expr * getDerefExpr(const Stmt *S)
Given that expression S represents a pointer that would be dereferenced, try to find a sub-expression...
void trackStoredValue(SVal V, const MemRegion *R, PathSensitiveBugReport &Report, TrackingOptions Opts={}, const StackFrame *Origin=nullptr)
Track how the value got stored into the given region and where it came from.
bool trackExpressionValue(const ExplodedNode *N, const Expr *E, PathSensitiveBugReport &R, TrackingOptions Opts={})
Attempts to add visitors to track expression value back to its point of origin.
TrackingKind
Specifies the type of tracking for an expression.
@ Thorough
Default tracking kind – specifies that as much information should be gathered about the tracked expre...
@ Condition
Specifies that a more moderate tracking should be used for the expression value.
IntrusiveRefCntPtr< const ProgramState > ProgramStateRef
@ OS
Indicates that the tracking object is a descendant of a referenced-counted OSObject,...
raw_ostream & operator<<(raw_ostream &os, const MemRegion *R)
Definition MemRegion.h:1696
std::shared_ptr< PathDiagnosticPiece > PathDiagnosticPieceRef
PRESERVE_NONE bool Ret(InterpState &S, CodePtr &PC)
Definition Interp.h:260
std::variant< struct RequiresDecl, struct HeaderDecl, struct UmbrellaDirDecl, struct ModuleDecl, struct ExcludeDecl, struct ExportDecl, struct ExportAsDecl, struct ExternModuleDecl, struct UseDecl, struct LinkDecl, struct ConfigMacrosDecl, struct ConflictDecl > Decl
All declarations that can appear in a module declaration.
The JSON file list parser is used to communicate input to InstallAPI.
@ Match
This is not an overload because the signature exactly matches an existing declaration.
Definition Sema.h:830
bool isa(CodeGen::Address addr)
Definition Address.h:330
std::pair< FileID, unsigned > FileIDAndOffset
Expr * Cond
};
U cast(CodeGen::Address addr)
Definition Address.h:327
@ ObjCSelf
Parameter for Objective-C 'self' argument.
Definition Decl.h:1745
Describes an event when the value got stored into a memory region.
@ Assignment
The value got stored into the region during assignment: int x; x = 42;.
@ CallArgument
The value got stored into the parameter region as the result of a call.
@ BlockCapture
The value got stored into the region as block capture.
@ Initialization
The value got stored into the region during initialization: int x = 42;.
const Expr * SourceOfTheValue
The expression where the value comes from.
const ExplodedNode * StoreSite
The node where the store happened.
Kind StoreKind
The type of store operation.
SVal Value
Symbolic value that is being stored.
const MemRegion * Dest
Memory regions involved in the store operation.
Describes a tracking result with the most basic information of what was actually done (or not done).
void combineWith(const Result &Other)
Combines the current result with the given result.
bool WasInterrupted
Signifies that the tracking was interrupted at some point.
Defines a set of options altering tracking behavior.
bool EnableNullFPSuppression
Specifies whether we should employ false positive suppression (inlined defensive checks,...
TrackingKind Kind
Specifies the kind of tracking.