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 // We don't need to check here, all these conditions were
1277 // checked by StoreSiteFinder, when it figured out that it is
1278 // initialization.
1279 const auto *DS =
1281
1282 if (SI.Value.isUndef()) {
1283 if (isa<VarRegion>(SI.Dest)) {
1284 const auto *VD = cast<VarDecl>(DS->getSingleDecl());
1285
1286 if (VD->getInit()) {
1287 OS << (HasPrefix ? "initialized" : "Initializing")
1288 << " to a garbage value";
1289 } else {
1290 OS << (HasPrefix ? "declared" : "Declaring")
1291 << " without an initial value";
1292 }
1293 }
1294 } else {
1295 OS << (HasPrefix ? "initialized" : "Initialized") << " here";
1296 }
1297 }
1298}
1299
1300/// Display diagnostics for passing bad region as a parameter.
1301static void showBRParamDiagnostics(llvm::raw_svector_ostream &OS,
1302 StoreInfo SI) {
1303 const auto *VR = cast<VarRegion>(SI.Dest);
1304 const auto *D = VR->getDecl();
1305
1306 OS << "Passing ";
1307
1308 if (auto CI = SI.Value.getAs<loc::ConcreteInt>()) {
1309 if (!*CI->getValue())
1310 OS << (isObjCPointer(D) ? "nil object reference" : "null pointer value");
1311 else
1312 OS << (isObjCPointer(D) ? "object reference of value " : "pointer value ")
1313 << DestTypeValue(SI, *CI);
1314
1315 } else if (SI.Value.isUndef()) {
1316 OS << "uninitialized value";
1317
1318 } else if (auto CI = SI.Value.getAs<nonloc::ConcreteInt>()) {
1319 OS << "the value " << CI->getValue();
1320
1321 } else if (SI.Origin && SI.Origin->canPrintPretty()) {
1322 SI.Origin->printPretty(OS);
1323
1324 } else {
1325 OS << "value";
1326 }
1327
1328 if (const auto *Param = dyn_cast<ParmVarDecl>(VR->getDecl())) {
1329 // Printed parameter indexes are 1-based, not 0-based.
1330 unsigned Idx = Param->getFunctionScopeIndex() + 1;
1331 OS << " via " << Idx << llvm::getOrdinalSuffix(Idx) << " parameter";
1332 if (VR->canPrintPretty()) {
1333 OS << " ";
1334 VR->printPretty(OS);
1335 }
1336 } else if (const auto *ImplParam = dyn_cast<ImplicitParamDecl>(D)) {
1337 if (ImplParam->getParameterKind() == ImplicitParamKind::ObjCSelf) {
1338 OS << " via implicit parameter 'self'";
1339 }
1340 }
1341}
1342
1343/// Show default diagnostics for storing bad region.
1344static void showBRDefaultDiagnostics(llvm::raw_svector_ostream &OS,
1345 StoreInfo SI) {
1346 const bool HasSuffix = SI.Dest->canPrintPretty();
1347
1348 if (auto CV = SI.Value.getAs<loc::ConcreteInt>()) {
1349 APSIntPtr V = CV->getValue();
1350 if (!*V)
1351 OS << (isObjCPointer(SI.Dest)
1352 ? "nil object reference stored"
1353 : (HasSuffix ? "Null pointer value stored"
1354 : "Storing null pointer value"));
1355 else {
1356 if (isObjCPointer(SI.Dest)) {
1357 OS << "object reference of value " << DestTypeValue(SI, *CV)
1358 << " stored";
1359 } else {
1360 if (HasSuffix)
1361 OS << "Pointer value of " << DestTypeValue(SI, *CV) << " stored";
1362 else
1363 OS << "Storing pointer value of " << DestTypeValue(SI, *CV);
1364 }
1365 }
1366 } else if (SI.Value.isUndef()) {
1367 OS << (HasSuffix ? "Uninitialized value stored"
1368 : "Storing uninitialized value");
1369
1370 } else if (auto CV = SI.Value.getAs<nonloc::ConcreteInt>()) {
1371 if (HasSuffix)
1372 OS << "The value " << CV->getValue() << " is assigned";
1373 else
1374 OS << "Assigning " << CV->getValue();
1375
1376 } else if (SI.Origin && SI.Origin->canPrintPretty()) {
1377 if (HasSuffix) {
1378 OS << "The value of ";
1379 SI.Origin->printPretty(OS);
1380 OS << " is assigned";
1381 } else {
1382 OS << "Assigning the value of ";
1383 SI.Origin->printPretty(OS);
1384 }
1385
1386 } else {
1387 OS << (HasSuffix ? "Value assigned" : "Assigning value");
1388 }
1389
1390 if (HasSuffix) {
1391 OS << " to ";
1392 SI.Dest->printPretty(OS);
1393 }
1394}
1395
1397 if (!CE)
1398 return false;
1399
1400 const auto *CtorDecl = CE->getConstructor();
1401
1402 return CtorDecl->isCopyOrMoveConstructor() && CtorDecl->isTrivial();
1403}
1404
1406 const MemRegion *R) {
1407
1408 const auto *TVR = dyn_cast_or_null<TypedValueRegion>(R);
1409
1410 if (!TVR)
1411 return nullptr;
1412
1413 const auto ITy = ILE->getType().getCanonicalType();
1414
1415 // Push each sub-region onto the stack.
1416 std::stack<const TypedValueRegion *> TVRStack;
1417 while (isa<FieldRegion>(TVR) || isa<ElementRegion>(TVR)) {
1418 // We found a region that matches the type of the init list,
1419 // so we assume this is the outer-most region. This can happen
1420 // if the initializer list is inside a class. If our assumption
1421 // is wrong, we return a nullptr in the end.
1422 if (ITy == TVR->getValueType().getCanonicalType())
1423 break;
1424
1425 TVRStack.push(TVR);
1426 TVR = cast<TypedValueRegion>(TVR->getSuperRegion());
1427 }
1428
1429 // If the type of the outer most region doesn't match the type
1430 // of the ILE, we can't match the ILE and the region.
1431 if (ITy != TVR->getValueType().getCanonicalType())
1432 return nullptr;
1433
1434 const Expr *Init = ILE;
1435 while (!TVRStack.empty()) {
1436 TVR = TVRStack.top();
1437 TVRStack.pop();
1438
1439 // We hit something that's not an init list before
1440 // running out of regions, so we most likely failed.
1441 if (!isa<InitListExpr>(Init))
1442 return nullptr;
1443
1444 ILE = cast<InitListExpr>(Init);
1445 auto NumInits = ILE->getNumInits();
1446
1447 if (const auto *FR = dyn_cast<FieldRegion>(TVR)) {
1448 const auto *FD = FR->getDecl();
1449
1450 if (FD->getFieldIndex() >= NumInits)
1451 return nullptr;
1452
1453 Init = ILE->getInit(FD->getFieldIndex());
1454 } else if (const auto *ER = dyn_cast<ElementRegion>(TVR)) {
1455 const auto Ind = ER->getIndex();
1456
1457 // If index is symbolic, we can't figure out which expression
1458 // belongs to the region.
1459 if (!Ind.isConstant())
1460 return nullptr;
1461
1462 const auto IndVal = Ind.getAsInteger()->getLimitedValue();
1463 if (IndVal >= NumInits)
1464 return nullptr;
1465
1466 Init = ILE->getInit(IndVal);
1467 }
1468 }
1469
1470 return Init;
1471}
1472
1473PathDiagnosticPieceRef StoreSiteFinder::VisitNode(const ExplodedNode *Succ,
1474 BugReporterContext &BRC,
1476 if (Satisfied)
1477 return nullptr;
1478
1479 const ExplodedNode *StoreSite = nullptr;
1480 const ExplodedNode *Pred = Succ->getFirstPred();
1481 const Expr *InitE = nullptr;
1482 bool IsParam = false;
1483
1484 // First see if we reached the declaration of the region.
1485 if (const auto *VR = dyn_cast<VarRegion>(R)) {
1486 if (isInitializationOfVar(Pred, VR)) {
1487 StoreSite = Pred;
1488 InitE = VR->getDecl()->getInit();
1489 }
1490 }
1491
1492 // If this is a post initializer expression, initializing the region, we
1493 // should track the initializer expression.
1494 if (std::optional<PostInitializer> PIP =
1495 Pred->getLocationAs<PostInitializer>()) {
1496 const MemRegion *FieldReg = (const MemRegion *)PIP->getLocationValue();
1497 if (FieldReg == R) {
1498 StoreSite = Pred;
1499 InitE = PIP->getInitializer()->getInit();
1500 }
1501 }
1502
1503 // Otherwise, see if this is the store site:
1504 // (1) Succ has this binding and Pred does not, i.e. this is
1505 // where the binding first occurred.
1506 // (2) Succ has this binding and is a PostStore node for this region, i.e.
1507 // the same binding was re-assigned here.
1508 if (!StoreSite) {
1509 if (Succ->getState()->getSVal(R) != V)
1510 return nullptr;
1511
1512 if (hasVisibleUpdate(Pred, Pred->getState()->getSVal(R), Succ, V)) {
1513 std::optional<PostStore> PS = Succ->getLocationAs<PostStore>();
1514 if (!PS || PS->getLocationValue() != R)
1515 return nullptr;
1516 }
1517
1518 StoreSite = Succ;
1519
1520 if (std::optional<PostStmt> P = Succ->getLocationAs<PostStmt>()) {
1521 // If this is an assignment expression, we can track the value
1522 // being assigned.
1523 if (const BinaryOperator *BO = P->getStmtAs<BinaryOperator>()) {
1524 if (BO->isAssignmentOp())
1525 InitE = BO->getRHS();
1526 }
1527 // If we have a declaration like 'S s{1,2}' that needs special
1528 // handling, we handle it here.
1529 else if (const auto *DS = P->getStmtAs<DeclStmt>()) {
1530 const auto *Decl = DS->getSingleDecl();
1531 if (isa<VarDecl>(Decl)) {
1532 const auto *VD = cast<VarDecl>(Decl);
1533
1534 // FIXME: Here we only track the inner most region, so we lose
1535 // information, but it's still better than a crash or no information
1536 // at all.
1537 //
1538 // E.g.: The region we have is 's.s2.s3.s4.y' and we only track 'y',
1539 // and throw away the rest.
1540 if (const auto *ILE = dyn_cast<InitListExpr>(VD->getInit()))
1541 InitE = tryExtractInitializerFromList(ILE, R);
1542 }
1543 } else if (const auto *CE = P->getStmtAs<CXXConstructExpr>()) {
1544
1545 const auto State = Succ->getState();
1546
1548 // Migrate the field regions from the current object to
1549 // the parent object. If we track 'a.y.e' and encounter
1550 // 'S a = b' then we need to track 'b.y.e'.
1551
1552 // Push the regions to a stack, from last to first, so
1553 // considering the example above the stack will look like
1554 // (bottom) 'e' -> 'y' (top).
1555
1556 std::stack<const SubRegion *> SRStack;
1557 const SubRegion *SR = cast<SubRegion>(R);
1558 while (isa<FieldRegion>(SR) || isa<ElementRegion>(SR)) {
1559 SRStack.push(SR);
1560 SR = cast<SubRegion>(SR->getSuperRegion());
1561 }
1562
1563 // Get the region for the object we copied/moved from.
1564 const auto *OriginEx = CE->getArg(0);
1565 const auto OriginVal =
1566 State->getSVal(OriginEx, Succ->getStackFrame());
1567
1568 // Pop the stored field regions and apply them to the origin
1569 // object in the same order we had them on the copy.
1570 // OriginField will evolve like 'b' -> 'b.y' -> 'b.y.e'.
1571 SVal OriginField = OriginVal;
1572 while (!SRStack.empty()) {
1573 const auto *TopR = SRStack.top();
1574 SRStack.pop();
1575
1576 if (const auto *FR = dyn_cast<FieldRegion>(TopR)) {
1577 OriginField = State->getLValue(FR->getDecl(), OriginField);
1578 } else if (const auto *ER = dyn_cast<ElementRegion>(TopR)) {
1579 OriginField = State->getLValue(ER->getElementType(),
1580 ER->getIndex(), OriginField);
1581 } else {
1582 // FIXME: handle other region type
1583 }
1584 }
1585
1586 // Track 'b.y.e'.
1587 getParentTracker().track(V, OriginField.getAsRegion(), Options);
1588 InitE = OriginEx;
1589 }
1590 }
1591 // This branch can occur in cases like `Ctor() : field{ x, y } {}'.
1592 else if (const auto *ILE = P->getStmtAs<InitListExpr>()) {
1593 // FIXME: Here we only track the top level region, so we lose
1594 // information, but it's still better than a crash or no information
1595 // at all.
1596 //
1597 // E.g.: The region we have is 's.s2.s3.s4.y' and we only track 'y', and
1598 // throw away the rest.
1599 InitE = tryExtractInitializerFromList(ILE, R);
1600 }
1601 }
1602
1603 // If this is a call entry, the variable should be a parameter.
1604 // FIXME: Handle CXXThisRegion as well. (This is not a priority because
1605 // 'this' should never be NULL, but this visitor isn't just for NULL and
1606 // UndefinedVal.)
1607 if (std::optional<CallEnter> CE = Succ->getLocationAs<CallEnter>()) {
1608 if (const auto *VR = dyn_cast<VarRegion>(R)) {
1609
1610 if (const auto *Param = dyn_cast<ParmVarDecl>(VR->getDecl())) {
1611 ProgramStateManager &StateMgr = BRC.getStateManager();
1612 CallEventManager &CallMgr = StateMgr.getCallEventManager();
1613
1615 CallMgr.getCaller(CE->getCalleeStackFrame(), Succ->getState());
1616 InitE = Call->getArgExpr(Param->getFunctionScopeIndex());
1617 } else {
1618 // Handle Objective-C 'self'.
1619 assert(isa<ImplicitParamDecl>(VR->getDecl()));
1620 InitE =
1621 cast<ObjCMessageExpr>(CE->getCalleeStackFrame()->getCallSite())
1622 ->getInstanceReceiver()
1623 ->IgnoreParenCasts();
1624 }
1625 IsParam = true;
1626 }
1627 }
1628
1629 // If this is a CXXTempObjectRegion, the Expr responsible for its creation
1630 // is wrapped inside of it.
1631 if (const auto *TmpR = dyn_cast<CXXTempObjectRegion>(R))
1632 InitE = TmpR->getExpr();
1633 }
1634
1635 if (!StoreSite)
1636 return nullptr;
1637
1638 Satisfied = true;
1639
1640 // If we have an expression that provided the value, try to track where it
1641 // came from.
1642 if (InitE) {
1643 if (!IsParam)
1644 InitE = InitE->IgnoreParenCasts();
1645
1646 getParentTracker().track(InitE, StoreSite, Options);
1647 }
1648
1649 // Let's try to find the region where the value came from.
1650 const MemRegion *OldRegion = nullptr;
1651
1652 // If we have init expression, it might be simply a reference
1653 // to a variable, so we can use it.
1654 if (InitE) {
1655 // That region might still be not exactly what we are looking for.
1656 // In situations like `int &ref = val;`, we can't say that
1657 // `ref` is initialized with `val`, rather refers to `val`.
1658 //
1659 // In order, to mitigate situations like this, we check if the last
1660 // stored value in that region is the value that we track.
1661 //
1662 // TODO: support other situations better.
1663 if (const MemRegion *Candidate =
1664 getLocationRegionIfReference(InitE, Succ, false)) {
1666
1667 // Here we traverse the graph up to find the last node where the
1668 // candidate region is still in the store.
1669 for (const ExplodedNode *N = StoreSite; N; N = N->getFirstPred()) {
1670 if (SM.includedInBindings(N->getState()->getStore(), Candidate)) {
1671 // And if it was bound to the target value, we can use it.
1672 if (N->getState()->getSVal(Candidate) == V) {
1673 OldRegion = Candidate;
1674 }
1675 break;
1676 }
1677 }
1678 }
1679 }
1680
1681 // Otherwise, if the current region does indeed contain the value
1682 // we are looking for, we can look for a region where this value
1683 // was before.
1684 //
1685 // It can be useful for situations like:
1686 // new = identity(old)
1687 // where the analyzer knows that 'identity' returns the value of its
1688 // first argument.
1689 //
1690 // NOTE: If the region R is not a simple var region, it can contain
1691 // V in one of its subregions.
1692 if (!OldRegion && StoreSite->getState()->getSVal(R) == V) {
1693 // Let's go up the graph to find the node where the region is
1694 // bound to V.
1695 const ExplodedNode *NodeWithoutBinding = StoreSite->getFirstPred();
1696 for (;
1697 NodeWithoutBinding && NodeWithoutBinding->getState()->getSVal(R) == V;
1698 NodeWithoutBinding = NodeWithoutBinding->getFirstPred()) {
1699 }
1700
1701 if (NodeWithoutBinding) {
1702 // Let's try to find a unique binding for the value in that node.
1703 // We want to use this to find unique bindings because of the following
1704 // situations:
1705 // b = a;
1706 // c = identity(b);
1707 //
1708 // Telling the user that the value of 'a' is assigned to 'c', while
1709 // correct, can be confusing.
1710 StoreManager::FindUniqueBinding FB(V.getAsLocSymbol());
1711 BRC.getStateManager().iterBindings(NodeWithoutBinding->getState(), FB);
1712 if (FB)
1713 OldRegion = FB.getRegion();
1714 }
1715 }
1716
1717 if (Options.Kind == TrackingKind::Condition && OriginSF &&
1718 !OriginSF->isParentOf(StoreSite->getStackFrame()))
1719 return nullptr;
1720
1721 // Okay, we've found the binding. Emit an appropriate message.
1722 SmallString<256> sbuf;
1723 llvm::raw_svector_ostream os(sbuf);
1724
1725 StoreInfo SI = {StoreInfo::Assignment, // default kind
1726 StoreSite,
1727 InitE,
1728 V,
1729 R,
1730 OldRegion};
1731
1732 if (std::optional<PostStmt> PS = StoreSite->getLocationAs<PostStmt>()) {
1733 const Stmt *S = PS->getStmt();
1734 const auto *DS = dyn_cast<DeclStmt>(S);
1735 const auto *VR = dyn_cast<VarRegion>(R);
1736
1737 if (DS) {
1739 } else if (const auto *BExpr = dyn_cast<BlockExpr>(S)) {
1741 if (VR) {
1742 // See if we can get the BlockVarRegion.
1743 ProgramStateRef State = StoreSite->getState();
1744 SVal V = StoreSite->getSVal(BExpr);
1745 if (const auto *BDR =
1746 dyn_cast_or_null<BlockDataRegion>(V.getAsRegion())) {
1747 if (const VarRegion *OriginalR = BDR->getOriginalRegion(VR)) {
1748 getParentTracker().track(State->getSVal(OriginalR), OriginalR,
1749 Options, OriginSF);
1750 }
1751 }
1752 }
1753 }
1754 } else if (SI.StoreSite->getLocation().getAs<CallEnter>() &&
1755 isa<VarRegion>(SI.Dest)) {
1757 }
1758
1759 return getParentTracker().handle(SI, BRC, Options);
1760}
1761
1762//===----------------------------------------------------------------------===//
1763// Implementation of TrackConstraintBRVisitor.
1764//===----------------------------------------------------------------------===//
1765
1766void TrackConstraintBRVisitor::Profile(llvm::FoldingSetNodeID &ID) const {
1767 static int tag = 0;
1768 ID.AddPointer(&tag);
1769 ID.AddString(Message);
1770 ID.AddBoolean(Assumption);
1771 ID.Add(Constraint);
1772}
1773
1774/// Return the tag associated with this visitor. This tag will be used
1775/// to make all PathDiagnosticPieces created by this visitor.
1777 return "TrackConstraintBRVisitor";
1778}
1779
1780bool TrackConstraintBRVisitor::isZeroCheck() const {
1781 return !Assumption && Constraint.getAs<Loc>();
1782}
1783
1784bool TrackConstraintBRVisitor::isUnderconstrained(const ExplodedNode *N) const {
1785 if (isZeroCheck())
1786 return N->getState()->isNull(Constraint).isUnderconstrained();
1787 return (bool)N->getState()->assume(Constraint, !Assumption);
1788}
1789
1792 const ExplodedNode *PrevN = N->getFirstPred();
1793 if (IsSatisfied)
1794 return nullptr;
1795
1796 // Start tracking after we see the first state in which the value is
1797 // constrained.
1798 if (!IsTrackingTurnedOn)
1799 if (!isUnderconstrained(N))
1800 IsTrackingTurnedOn = true;
1801 if (!IsTrackingTurnedOn)
1802 return nullptr;
1803
1804 // Check if in the previous state it was feasible for this constraint
1805 // to *not* be true.
1806 if (isUnderconstrained(PrevN)) {
1807 IsSatisfied = true;
1808
1809 // At this point, the negation of the constraint should be infeasible. If it
1810 // is feasible, make sure that the negation of the constrainti was
1811 // infeasible in the current state. If it is feasible, we somehow missed
1812 // the transition point.
1813 assert(!isUnderconstrained(N));
1814
1815 // Construct a new PathDiagnosticPiece.
1816 ProgramPoint P = N->getLocation();
1817
1818 // If this node already have a specialized note, it's probably better
1819 // than our generic note.
1820 // FIXME: This only looks for note tags, not for other ways to add a note.
1821 if (isa_and_nonnull<NoteTag>(P.getTag()))
1822 return nullptr;
1823
1826 if (!L.isValid())
1827 return nullptr;
1828
1829 auto X = std::make_shared<PathDiagnosticEventPiece>(L, Message);
1830 X->setTag(getTag());
1831 return std::move(X);
1832 }
1833
1834 return nullptr;
1835}
1836
1837//===----------------------------------------------------------------------===//
1838// Implementation of SuppressInlineDefensiveChecksVisitor.
1839//===----------------------------------------------------------------------===//
1840
1843 : V(Value) {
1844 // Check if the visitor is disabled.
1845 AnalyzerOptions &Options = N->getState()->getAnalysisManager().options;
1846 if (!Options.ShouldSuppressInlinedDefensiveChecks)
1847 IsSatisfied = true;
1848}
1849
1851 llvm::FoldingSetNodeID &ID) const {
1852 static int id = 0;
1853 ID.AddPointer(&id);
1854 ID.Add(V);
1855}
1856
1858 return "IDCVisitor";
1859}
1860
1863 BugReporterContext &BRC,
1865 const ExplodedNode *Pred = Succ->getFirstPred();
1866 if (IsSatisfied)
1867 return nullptr;
1868
1869 // Start tracking after we see the first state in which the value is null.
1870 if (!IsTrackingTurnedOn)
1871 if (Succ->getState()->isNull(V).isConstrainedTrue())
1872 IsTrackingTurnedOn = true;
1873 if (!IsTrackingTurnedOn)
1874 return nullptr;
1875
1876 // Check if in the previous state it was feasible for this value
1877 // to *not* be null.
1878 if (!Pred->getState()->isNull(V).isConstrainedTrue() &&
1879 Succ->getState()->isNull(V).isConstrainedTrue()) {
1880 IsSatisfied = true;
1881
1882 // Check if this is inlined defensive checks.
1883 const StackFrame *CurSF = Succ->getStackFrame();
1884 const StackFrame *ReportSF = BR.getErrorNode()->getStackFrame();
1885 if (CurSF != ReportSF && !CurSF->isParentOf(ReportSF)) {
1886 BR.markInvalid("Suppress IDC", CurSF);
1887 return nullptr;
1888 }
1889
1890 // Treat defensive checks in function-like macros as if they were an inlined
1891 // defensive check. If the bug location is not in a macro and the
1892 // terminator for the current location is in a macro then suppress the
1893 // warning.
1894 auto BugPoint = BR.getErrorNode()->getLocation().getAs<StmtPoint>();
1895
1896 if (!BugPoint)
1897 return nullptr;
1898
1899 ProgramPoint CurPoint = Succ->getLocation();
1900 const Stmt *CurTerminatorStmt = nullptr;
1901 if (auto BE = CurPoint.getAs<BlockEdge>()) {
1902 CurTerminatorStmt = BE->getSrc()->getTerminator().getStmt();
1903 } else if (auto SP = CurPoint.getAs<StmtPoint>()) {
1904 const Stmt *CurStmt = SP->getStmt();
1905 if (!CurStmt->getBeginLoc().isMacroID())
1906 return nullptr;
1907
1908 const CFGStmtMap *Map = CurSF->getAnalysisDeclContext()->getCFGStmtMap();
1909 CurTerminatorStmt = Map->getBlock(CurStmt)->getTerminatorStmt();
1910 } else {
1911 return nullptr;
1912 }
1913
1914 if (!CurTerminatorStmt)
1915 return nullptr;
1916
1917 SourceLocation TerminatorLoc = CurTerminatorStmt->getBeginLoc();
1918 if (TerminatorLoc.isMacroID()) {
1919 SourceLocation BugLoc = BugPoint->getStmt()->getBeginLoc();
1920
1921 // Suppress reports unless we are in that same macro.
1922 if (!BugLoc.isMacroID() ||
1923 getMacroName(BugLoc, BRC) != getMacroName(TerminatorLoc, BRC)) {
1924 BR.markInvalid("Suppress Macro IDC", CurSF);
1925 }
1926 return nullptr;
1927 }
1928 }
1929 return nullptr;
1930}
1931
1932//===----------------------------------------------------------------------===//
1933// TrackControlDependencyCondBRVisitor.
1934//===----------------------------------------------------------------------===//
1935
1936namespace {
1937/// Tracks the expressions that are a control dependency of the node that was
1938/// supplied to the constructor.
1939/// For example:
1940///
1941/// cond = 1;
1942/// if (cond)
1943/// 10 / 0;
1944///
1945/// An error is emitted at line 3. This visitor realizes that the branch
1946/// on line 2 is a control dependency of line 3, and tracks it's condition via
1947/// trackExpressionValue().
1948class TrackControlDependencyCondBRVisitor final
1950 const ExplodedNode *Origin;
1951 ControlDependencyCalculator ControlDeps;
1953
1954public:
1955 TrackControlDependencyCondBRVisitor(TrackerRef ParentTracker,
1956 const ExplodedNode *O)
1957 : TrackingBugReporterVisitor(ParentTracker), Origin(O),
1958 ControlDeps(&O->getCFG()) {}
1959
1960 void Profile(llvm::FoldingSetNodeID &ID) const override {
1961 static int x = 0;
1962 ID.AddPointer(&x);
1963 }
1964
1965 PathDiagnosticPieceRef VisitNode(const ExplodedNode *N,
1966 BugReporterContext &BRC,
1967 PathSensitiveBugReport &BR) override;
1968};
1969} // end of anonymous namespace
1970
1971static std::shared_ptr<PathDiagnosticEventPiece>
1973 const ExplodedNode *N,
1974 BugReporterContext &BRC) {
1975
1977 !BRC.getAnalyzerOptions().ShouldTrackConditionsDebug)
1978 return nullptr;
1979
1980 std::string ConditionText = std::string(Lexer::getSourceText(
1981 CharSourceRange::getTokenRange(Cond->getSourceRange()),
1983
1984 return std::make_shared<PathDiagnosticEventPiece>(
1986 N->getStackFrame()),
1987 (Twine() + "Tracking condition '" + ConditionText + "'").str());
1988}
1989
1990static bool isAssertlikeBlock(const CFGBlock *B, ASTContext &Context) {
1991 if (B->succ_size() != 2)
1992 return false;
1993
1994 const CFGBlock *Then = B->succ_begin()->getReachableBlock();
1995 const CFGBlock *Else = (B->succ_begin() + 1)->getReachableBlock();
1996
1997 if (!Then || !Else)
1998 return false;
1999
2000 if (Then->isInevitablySinking() != Else->isInevitablySinking())
2001 return true;
2002
2003 // For the following condition the following CFG would be built:
2004 //
2005 // ------------->
2006 // / \
2007 // [B1] -> [B2] -> [B3] -> [sink]
2008 // assert(A && B || C); \ \
2009 // -----------> [go on with the execution]
2010 //
2011 // It so happens that CFGBlock::getTerminatorCondition returns 'A' for block
2012 // B1, 'A && B' for B2, and 'A && B || C' for B3. Let's check whether we
2013 // reached the end of the condition!
2014 if (const Stmt *ElseCond = Else->getTerminatorCondition())
2015 if (const auto *BinOp = dyn_cast<BinaryOperator>(ElseCond))
2016 if (BinOp->isLogicalOp())
2017 return isAssertlikeBlock(Else, Context);
2018
2019 return false;
2020}
2021
2023TrackControlDependencyCondBRVisitor::VisitNode(const ExplodedNode *N,
2024 BugReporterContext &BRC,
2026 // We can only reason about control dependencies within the same stack frame.
2027 if (Origin->getStackFrame() != N->getStackFrame())
2028 return nullptr;
2029
2030 CFGBlock *NB = const_cast<CFGBlock *>(N->getCFGBlock());
2031
2032 // Skip if we already inspected this block.
2033 if (!VisitedBlocks.insert(NB).second)
2034 return nullptr;
2035
2036 CFGBlock *OriginB = const_cast<CFGBlock *>(Origin->getCFGBlock());
2037
2038 // TODO: Cache CFGBlocks for each ExplodedNode.
2039 if (!OriginB || !NB)
2040 return nullptr;
2041
2042 if (isAssertlikeBlock(NB, BRC.getASTContext()))
2043 return nullptr;
2044
2045 if (ControlDeps.isControlDependent(OriginB, NB)) {
2046 // We don't really want to explain for range loops. Evidence suggests that
2047 // the only thing that leads to is the addition of calls to operator!=.
2048 if (llvm::isa_and_nonnull<CXXForRangeStmt>(NB->getTerminatorStmt()))
2049 return nullptr;
2050
2051 if (const Expr *Condition = NB->getLastCondition()) {
2052
2053 // If we can't retrieve a sensible condition, just bail out.
2054 const Expr *InnerExpr = peelOffOuterExpr(Condition, N);
2055 if (!InnerExpr)
2056 return nullptr;
2057
2058 // If the condition was a function call, we likely won't gain much from
2059 // tracking it either. Evidence suggests that it will mostly trigger in
2060 // scenarios like this:
2061 //
2062 // void f(int *x) {
2063 // x = nullptr;
2064 // if (alwaysTrue()) // We don't need a whole lot of explanation
2065 // // here, the function name is good enough.
2066 // *x = 5;
2067 // }
2068 //
2069 // Its easy to create a counterexample where this heuristic would make us
2070 // lose valuable information, but we've never really seen one in practice.
2071 if (isa<CallExpr>(InnerExpr))
2072 return nullptr;
2073
2074 // Keeping track of the already tracked conditions on a visitor level
2075 // isn't sufficient, because a new visitor is created for each tracked
2076 // expression, hence the BugReport level set.
2077 if (BR.addTrackedCondition(N)) {
2078 getParentTracker().track(InnerExpr, N,
2080 /*EnableNullFPSuppression=*/false});
2082 }
2083 }
2084 }
2085
2086 return nullptr;
2087}
2088
2089//===----------------------------------------------------------------------===//
2090// Implementation of trackExpressionValue.
2091//===----------------------------------------------------------------------===//
2092
2093static const Expr *peelOffOuterExpr(const Expr *Ex, const ExplodedNode *N) {
2094
2095 Ex = Ex->IgnoreParenCasts();
2096 if (const auto *FE = dyn_cast<FullExpr>(Ex))
2097 return peelOffOuterExpr(FE->getSubExpr(), N);
2098 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(Ex))
2099 return peelOffOuterExpr(OVE->getSourceExpr(), N);
2100 if (const auto *POE = dyn_cast<PseudoObjectExpr>(Ex)) {
2101 const auto *PropRef = dyn_cast<ObjCPropertyRefExpr>(POE->getSyntacticForm());
2102 if (PropRef && PropRef->isMessagingGetter()) {
2103 const Expr *GetterMessageSend =
2104 POE->getSemanticExpr(POE->getNumSemanticExprs() - 1);
2105 assert(isa<ObjCMessageExpr>(GetterMessageSend->IgnoreParenCasts()));
2106 return peelOffOuterExpr(GetterMessageSend, N);
2107 }
2108 }
2109
2110 // Peel off the ternary operator.
2111 if (const auto *CO = dyn_cast<ConditionalOperator>(Ex)) {
2112 // Find a node where the branching occurred and find out which branch
2113 // we took (true/false) by looking at the ExplodedGraph.
2114 const ExplodedNode *NI = N;
2115 do {
2116 ProgramPoint ProgPoint = NI->getLocation();
2117 if (std::optional<BlockEdge> BE = ProgPoint.getAs<BlockEdge>()) {
2118 const CFGBlock *srcBlk = BE->getSrc();
2119 if (const Stmt *term = srcBlk->getTerminatorStmt()) {
2120 if (term == CO) {
2121 bool TookTrueBranch = (*(srcBlk->succ_begin()) == BE->getDst());
2122 if (TookTrueBranch)
2123 return peelOffOuterExpr(CO->getTrueExpr(), N);
2124 else
2125 return peelOffOuterExpr(CO->getFalseExpr(), N);
2126 }
2127 }
2128 }
2129 NI = NI->getFirstPred();
2130 } while (NI);
2131 }
2132
2133 if (auto *BO = dyn_cast<BinaryOperator>(Ex))
2134 if (const Expr *SubEx = peelOffPointerArithmetic(BO))
2135 return peelOffOuterExpr(SubEx, N);
2136
2137 if (auto *UO = dyn_cast<UnaryOperator>(Ex)) {
2138 if (UO->getOpcode() == UO_LNot)
2139 return peelOffOuterExpr(UO->getSubExpr(), N);
2140
2141 // FIXME: There's a hack in our Store implementation that always computes
2142 // field offsets around null pointers as if they are always equal to 0.
2143 // The idea here is to report accesses to fields as null dereferences
2144 // even though the pointer value that's being dereferenced is actually
2145 // the offset of the field rather than exactly 0.
2146 // See the FIXME in StoreManager's getLValueFieldOrIvar() method.
2147 // This code interacts heavily with this hack; otherwise the value
2148 // would not be null at all for most fields, so we'd be unable to track it.
2149 if (UO->getOpcode() == UO_AddrOf && UO->getSubExpr()->isLValue())
2150 if (const Expr *DerefEx = bugreporter::getDerefExpr(UO->getSubExpr()))
2151 return peelOffOuterExpr(DerefEx, N);
2152 }
2153
2154 return Ex;
2155}
2156
2157/// Find the ExplodedNode where the lvalue (the value of 'Ex')
2158/// was computed.
2160 const Expr *Inner) {
2161 while (N) {
2162 if (N->getStmtForDiagnostics() == Inner)
2163 return N;
2164 N = N->getFirstPred();
2165 }
2166 return N;
2167}
2168
2169//===----------------------------------------------------------------------===//
2170// Tracker implementation
2171//===----------------------------------------------------------------------===//
2172
2174 BugReporterContext &BRC,
2175 StringRef NodeText) {
2176 // Construct a new PathDiagnosticPiece.
2179 if (P.getAs<CallEnter>() && SI.SourceOfTheValue)
2181 P.getStackFrame());
2182
2183 if (!L.isValid() || !L.asLocation().isValid())
2185
2186 if (!L.isValid() || !L.asLocation().isValid())
2187 return nullptr;
2188
2189 return std::make_shared<PathDiagnosticEventPiece>(L, NodeText);
2190}
2191
2192namespace {
2193class DefaultStoreHandler final : public StoreHandler {
2194public:
2196
2198 TrackingOptions Opts) override {
2199 // Okay, we've found the binding. Emit an appropriate message.
2200 SmallString<256> Buffer;
2201 llvm::raw_svector_ostream OS(Buffer);
2202
2203 switch (SI.StoreKind) {
2206 showBRDiagnostics(OS, SI);
2207 break;
2210 break;
2213 break;
2214 }
2215
2218
2219 return constructNote(SI, BRC, OS.str());
2220 }
2221};
2222
2223class ControlDependencyHandler final : public ExpressionHandler {
2224public:
2226
2227 Tracker::Result handle(const Expr *Inner, const ExplodedNode *InputNode,
2228 const ExplodedNode *LVNode,
2229 TrackingOptions Opts) override {
2230 PathSensitiveBugReport &Report = getParentTracker().getReport();
2231
2232 // We only track expressions if we believe that they are important. Chances
2233 // are good that control dependencies to the tracking point are also
2234 // important because of this, let's explain why we believe control reached
2235 // this point.
2236 // TODO: Shouldn't we track control dependencies of every bug location,
2237 // rather than only tracked expressions?
2238 if (LVNode->getState()
2239 ->getAnalysisManager()
2240 .getAnalyzerOptions()
2241 .ShouldTrackConditions) {
2242 Report.addVisitor<TrackControlDependencyCondBRVisitor>(
2243 &getParentTracker(), InputNode);
2244 return {/*FoundSomethingToTrack=*/true};
2245 }
2246
2247 return {};
2248 }
2249};
2250
2251class NilReceiverHandler final : public ExpressionHandler {
2252public:
2254
2255 Tracker::Result handle(const Expr *Inner, const ExplodedNode *InputNode,
2256 const ExplodedNode *LVNode,
2257 TrackingOptions Opts) override {
2258 // The message send could be nil due to the receiver being nil.
2259 // At this point in the path, the receiver should be live since we are at
2260 // the message send expr. If it is nil, start tracking it.
2261 if (const Expr *Receiver =
2263 return getParentTracker().track(Receiver, LVNode, Opts);
2264
2265 return {};
2266 }
2267};
2268
2269class ArrayIndexHandler final : public ExpressionHandler {
2270public:
2272
2273 Tracker::Result handle(const Expr *Inner, const ExplodedNode *InputNode,
2274 const ExplodedNode *LVNode,
2275 TrackingOptions Opts) override {
2276 // Track the index if this is an array subscript.
2277 if (const auto *Arr = dyn_cast<ArraySubscriptExpr>(Inner))
2278 return getParentTracker().track(
2279 Arr->getIdx(), LVNode,
2280 {Opts.Kind, /*EnableNullFPSuppression*/ false});
2281
2282 return {};
2283 }
2284};
2285
2286// TODO: extract it into more handlers
2287class InterestingLValueHandler final : public ExpressionHandler {
2288public:
2290
2291 Tracker::Result handle(const Expr *Inner, const ExplodedNode *InputNode,
2292 const ExplodedNode *LVNode,
2293 TrackingOptions Opts) override {
2294 ProgramStateRef LVState = LVNode->getState();
2295 const StackFrame *SF = LVNode->getStackFrame();
2296 PathSensitiveBugReport &Report = getParentTracker().getReport();
2297 Tracker::Result Result;
2298
2299 // See if the expression we're interested refers to a variable.
2300 // If so, we can track both its contents and constraints on its value.
2302 SVal LVal = LVNode->getSVal(Inner);
2303
2304 const MemRegion *RR = getLocationRegionIfReference(Inner, LVNode);
2305 bool LVIsNull = LVState->isNull(LVal).isConstrainedTrue();
2306
2307 // If this is a C++ reference to a null pointer, we are tracking the
2308 // pointer. In addition, we should find the store at which the reference
2309 // got initialized.
2310 if (RR && !LVIsNull)
2311 Result.combineWith(getParentTracker().track(LVal, RR, Opts, SF));
2312
2313 // In case of C++ references, we want to differentiate between a null
2314 // reference and reference to null pointer.
2315 // If the LVal is null, check if we are dealing with null reference.
2316 // For those, we want to track the location of the reference.
2317 const MemRegion *R =
2318 (RR && LVIsNull) ? RR : LVNode->getSVal(Inner).getAsRegion();
2319
2320 if (R) {
2321
2322 // Mark both the variable region and its contents as interesting.
2323 SVal V = LVState->getRawSVal(loc::MemRegionVal(R));
2324 Report.addVisitor<NoStoreFuncVisitor>(cast<SubRegion>(R), Opts.Kind);
2325
2326 // When we got here, we do have something to track, and we will
2327 // interrupt.
2328 Result.FoundSomethingToTrack = true;
2329 Result.WasInterrupted = true;
2330
2331 MacroNullReturnSuppressionVisitor::addMacroVisitorIfNecessary(
2332 LVNode, R, Opts.EnableNullFPSuppression, Report, V);
2333
2334 Report.markInteresting(V, Opts.Kind);
2335 Report.addVisitor<UndefOrNullArgVisitor>(R);
2336
2337 // If the contents are symbolic and null, find out when they became
2338 // null.
2339 if (V.getAsLocSymbol(/*IncludeBaseRegions=*/true))
2340 if (LVState->isNull(V).isConstrainedTrue())
2341 Report.addVisitor<TrackConstraintBRVisitor>(
2342 V.castAs<DefinedSVal>(),
2343 /*Assumption=*/false, "Assuming pointer value is null");
2344
2345 // Add visitor, which will suppress inline defensive checks.
2346 if (auto DV = V.getAs<DefinedSVal>())
2347 if (!DV->isZeroConstant() && Opts.EnableNullFPSuppression)
2348 // Note that LVNode may be too late (i.e., too far from the
2349 // InputNode) because the lvalue may have been computed before the
2350 // inlined call was evaluated. InputNode may as well be too early
2351 // here, because the symbol is already dead; this, however, is fine
2352 // because we can still find the node in which it collapsed to null
2353 // previously.
2354 Report.addVisitor<SuppressInlineDefensiveChecksVisitor>(*DV,
2355 InputNode);
2356 getParentTracker().track(V, R, Opts, SF);
2357 }
2358 }
2359
2360 return Result;
2361 }
2362};
2363
2364/// Adds a ReturnVisitor if the given statement represents a call that was
2365/// inlined.
2366///
2367/// This will search back through the ExplodedGraph, starting from the given
2368/// node, looking for when the given statement was processed. If it turns out
2369/// the statement is a call that was inlined, we add the visitor to the
2370/// bug report, so it can print a note later.
2371class InlinedFunctionCallHandler final : public ExpressionHandler {
2373
2374 Tracker::Result handle(const Expr *E, const ExplodedNode *InputNode,
2375 const ExplodedNode *ExprNode,
2376 TrackingOptions Opts) override {
2377 if (!CallEvent::isCallStmt(E))
2378 return {};
2379
2380 // First, find when we processed the statement.
2381 // If we work with a 'CXXNewExpr' that is going to be purged away before
2382 // its call take place. We would catch that purge in the last condition
2383 // as a 'StmtPoint' so we have to bypass it.
2384 const bool BypassCXXNewExprEval = isa<CXXNewExpr>(E);
2385
2386 // This is moving forward when we enter into another stack frame.
2387 const StackFrame *CurrentSF = ExprNode->getStackFrame();
2388
2389 do {
2390 // If that is satisfied we found our statement as an inlined call.
2391 if (std::optional<CallExitEnd> CEE =
2392 ExprNode->getLocationAs<CallExitEnd>())
2393 if (CEE->getCalleeStackFrame()->getCallSite() == E)
2394 break;
2395
2396 // Try to move forward to the end of the call-chain.
2397 ExprNode = ExprNode->getFirstPred();
2398 if (!ExprNode)
2399 break;
2400
2401 const StackFrame *PredSF = ExprNode->getStackFrame();
2402
2403 // If that is satisfied we found our statement.
2404 // FIXME: This code currently bypasses the call site for the
2405 // conservatively evaluated allocator.
2406 if (!BypassCXXNewExprEval)
2407 if (std::optional<StmtPoint> SP = ExprNode->getLocationAs<StmtPoint>())
2408 // See if we do not enter into another stack frame.
2409 if (SP->getStmt() == E && CurrentSF == PredSF)
2410 break;
2411
2412 CurrentSF = PredSF;
2413 } while (ExprNode->getStackFrame() == CurrentSF);
2414
2415 // Next, step over any post-statement checks.
2416 while (ExprNode && ExprNode->getLocation().getAs<PostStmt>())
2417 ExprNode = ExprNode->getFirstPred();
2418 if (!ExprNode)
2419 return {};
2420
2421 // Finally, see if we inlined the call.
2422 std::optional<CallExitEnd> CEE = ExprNode->getLocationAs<CallExitEnd>();
2423 if (!CEE)
2424 return {};
2425
2426 const StackFrame *CalleeSF = CEE->getCalleeStackFrame();
2427 if (CalleeSF->getCallSite() != E)
2428 return {};
2429
2430 // Check the return value.
2431 ProgramStateRef State = ExprNode->getState();
2432 SVal RetVal = ExprNode->getSVal(E);
2433
2434 // Handle cases where a reference is returned and then immediately used.
2435 if (cast<Expr>(E)->isGLValue())
2436 if (std::optional<Loc> LValue = RetVal.getAs<Loc>())
2437 RetVal = State->getSVal(*LValue);
2438
2439 // See if the return value is NULL. If so, suppress the report.
2440 AnalyzerOptions &Options = State->getAnalysisManager().options;
2441
2442 bool EnableNullFPSuppression = false;
2443 if (Opts.EnableNullFPSuppression && Options.ShouldSuppressNullReturnPaths)
2444 if (std::optional<Loc> RetLoc = RetVal.getAs<Loc>())
2445 EnableNullFPSuppression = State->isNull(*RetLoc).isConstrainedTrue();
2446
2447 PathSensitiveBugReport &Report = getParentTracker().getReport();
2448 Report.addVisitor<ReturnVisitor>(&getParentTracker(), CalleeSF,
2449 EnableNullFPSuppression, Options,
2450 Opts.Kind);
2451 return {true};
2452 }
2453};
2454
2455class DefaultExpressionHandler final : public ExpressionHandler {
2456public:
2458
2459 Tracker::Result handle(const Expr *Inner, const ExplodedNode *InputNode,
2460 const ExplodedNode *LVNode,
2461 TrackingOptions Opts) override {
2462 ProgramStateRef LVState = LVNode->getState();
2463 const StackFrame *SF = LVNode->getStackFrame();
2464 PathSensitiveBugReport &Report = getParentTracker().getReport();
2465 Tracker::Result Result;
2466
2467 // If the expression is not an "lvalue expression", we can still
2468 // track the constraints on its contents.
2469 SVal V = LVState->getSValAsScalarOrLoc(Inner, LVNode->getStackFrame());
2470
2471 // Is it a symbolic value?
2472 if (auto L = V.getAs<loc::MemRegionVal>()) {
2473 // FIXME: this is a hack for fixing a later crash when attempting to
2474 // dereference a void* pointer.
2475 // We should not try to dereference pointers at all when we don't care
2476 // what is written inside the pointer.
2477 bool CanDereference = true;
2478 if (const auto *SR = L->getRegionAs<SymbolicRegion>()) {
2479 if (SR->getPointeeStaticType()->isVoidType())
2480 CanDereference = false;
2481 } else if (L->getRegionAs<AllocaRegion>())
2482 CanDereference = false;
2483
2484 // At this point we are dealing with the region's LValue.
2485 // However, if the rvalue is a symbolic region, we should track it as
2486 // well. Try to use the correct type when looking up the value.
2487 SVal RVal;
2489 RVal = LVState->getRawSVal(*L, Inner->getType());
2490 else if (CanDereference)
2491 RVal = LVState->getSVal(L->getRegion());
2492
2493 if (CanDereference) {
2494 Report.addVisitor<UndefOrNullArgVisitor>(L->getRegion());
2495 Result.FoundSomethingToTrack = true;
2496
2497 if (!RVal.isUnknown())
2498 Result.combineWith(
2499 getParentTracker().track(RVal, L->getRegion(), Opts, SF));
2500 }
2501
2502 const MemRegion *RegionRVal = RVal.getAsRegion();
2503 if (isa_and_nonnull<SymbolicRegion>(RegionRVal)) {
2504 Report.markInteresting(RegionRVal, Opts.Kind);
2505 Report.addVisitor<TrackConstraintBRVisitor>(
2506 loc::MemRegionVal(RegionRVal),
2507 /*Assumption=*/false, "Assuming pointer value is null");
2508 Result.FoundSomethingToTrack = true;
2509 }
2510 }
2511
2512 return Result;
2513 }
2514};
2515
2516/// Attempts to add visitors to track an RValue expression back to its point of
2517/// origin.
2518class PRValueHandler final : public ExpressionHandler {
2519public:
2521
2522 Tracker::Result handle(const Expr *E, const ExplodedNode *InputNode,
2523 const ExplodedNode *ExprNode,
2524 TrackingOptions Opts) override {
2525 if (!E->isPRValue())
2526 return {};
2527
2528 const ExplodedNode *RVNode = findNodeForExpression(ExprNode, E);
2529 if (!RVNode)
2530 return {};
2531
2532 Tracker::Result CombinedResult;
2533 Tracker &Parent = getParentTracker();
2534
2535 const auto track = [&CombinedResult, &Parent, ExprNode,
2536 Opts](const Expr *Inner) {
2537 CombinedResult.combineWith(Parent.track(Inner, ExprNode, Opts));
2538 };
2539
2540 // FIXME: Initializer lists can appear in many different contexts
2541 // and most of them needs a special handling. For now let's handle
2542 // what we can. If the initializer list only has 1 element, we track
2543 // that.
2544 // This snippet even handles nesting, e.g.: int *x{{{{{y}}}}};
2545 if (const auto *ILE = dyn_cast<InitListExpr>(E)) {
2546 if (ILE->getNumInits() == 1) {
2547 track(ILE->getInit(0));
2548
2549 return CombinedResult;
2550 }
2551
2552 return {};
2553 }
2554
2555 ProgramStateRef RVState = RVNode->getState();
2556 SVal V = RVState->getSValAsScalarOrLoc(E, RVNode->getStackFrame());
2557 const auto *BO = dyn_cast<BinaryOperator>(E);
2558
2559 if (!BO || !BO->isMultiplicativeOp() || !V.isZeroConstant())
2560 return {};
2561
2562 SVal RHSV = RVState->getSVal(BO->getRHS(), RVNode->getStackFrame());
2563 SVal LHSV = RVState->getSVal(BO->getLHS(), RVNode->getStackFrame());
2564
2565 // Track both LHS and RHS of a multiplication.
2566 if (BO->getOpcode() == BO_Mul) {
2567 if (LHSV.isZeroConstant())
2568 track(BO->getLHS());
2569 if (RHSV.isZeroConstant())
2570 track(BO->getRHS());
2571 } else { // Track only the LHS of a division or a modulo.
2572 if (LHSV.isZeroConstant())
2573 track(BO->getLHS());
2574 }
2575
2576 return CombinedResult;
2577 }
2578};
2579} // namespace
2580
2593
2595 TrackingOptions Opts) {
2596 if (!E || !N)
2597 return {};
2598
2599 const Expr *Inner = peelOffOuterExpr(E, N);
2600 const ExplodedNode *LVNode = findNodeForExpression(N, Inner);
2601 if (!LVNode)
2602 return {};
2603
2604 Result CombinedResult;
2605 // Iterate through the handlers in the order according to their priorities.
2606 for (ExpressionHandlerPtr &Handler : ExpressionHandlers) {
2607 CombinedResult.combineWith(Handler->handle(Inner, N, LVNode, Opts));
2608 if (CombinedResult.WasInterrupted) {
2609 // There is no need to confuse our users here.
2610 // We got interrupted, but our users don't need to know about it.
2611 CombinedResult.WasInterrupted = false;
2612 break;
2613 }
2614 }
2615
2616 return CombinedResult;
2617}
2618
2620 const StackFrame *Origin) {
2621 if (!V.isUnknown()) {
2622 Report.addVisitor<StoreSiteFinder>(this, V, R, Opts, Origin);
2623 return {true};
2624 }
2625 return {};
2626}
2627
2629 TrackingOptions Opts) {
2630 // Iterate through the handlers in the order according to their priorities.
2631 for (StoreHandlerPtr &Handler : StoreHandlers) {
2632 if (PathDiagnosticPieceRef Result = Handler->handle(SI, BRC, Opts))
2633 // If the handler produced a non-null piece, return it.
2634 // There is no need in asking other handlers.
2635 return Result;
2636 }
2637 return {};
2638}
2639
2641 const Expr *E,
2642
2644 TrackingOptions Opts) {
2645 return Tracker::create(Report)
2646 ->track(E, InputNode, Opts)
2647 .FoundSomethingToTrack;
2648}
2649
2652 TrackingOptions Opts,
2653 const StackFrame *Origin) {
2654 Tracker::create(Report)->track(V, R, Opts, Origin);
2655}
2656
2657//===----------------------------------------------------------------------===//
2658// Implementation of NulReceiverBRVisitor.
2659//===----------------------------------------------------------------------===//
2660
2662 const ExplodedNode *N) {
2663 const auto *ME = dyn_cast<ObjCMessageExpr>(S);
2664 if (!ME)
2665 return nullptr;
2666 if (const Expr *Receiver = ME->getInstanceReceiver()) {
2667 ProgramStateRef state = N->getState();
2668 SVal V = N->getSVal(Receiver);
2669 if (state->isNull(V).isConstrainedTrue())
2670 return Receiver;
2671 }
2672 return nullptr;
2673}
2674
2678 std::optional<PreStmt> P = N->getLocationAs<PreStmt>();
2679 if (!P)
2680 return nullptr;
2681
2682 const Stmt *S = P->getStmt();
2683 const Expr *Receiver = getNilReceiver(S, N);
2684 if (!Receiver)
2685 return nullptr;
2686
2688 llvm::raw_svector_ostream OS(Buf);
2689
2690 if (const auto *ME = dyn_cast<ObjCMessageExpr>(S)) {
2691 OS << "'";
2692 ME->getSelector().print(OS);
2693 OS << "' not called";
2694 }
2695 else {
2696 OS << "No method is called";
2697 }
2698 OS << " because the receiver is nil";
2699
2700 // The receiver was nil, and hence the method was skipped.
2701 // Register a BugReporterVisitor to issue a message telling us how
2702 // the receiver was null.
2703 bugreporter::trackExpressionValue(N, Receiver, BR,
2705 /*EnableNullFPSuppression*/ false});
2706 // Issue a message saying that the method was skipped.
2707 PathDiagnosticLocation L(Receiver, BRC.getSourceManager(),
2708 N->getStackFrame());
2709 return std::make_shared<PathDiagnosticEventPiece>(L, OS.str());
2710}
2711
2712//===----------------------------------------------------------------------===//
2713// Visitor that tries to report interesting diagnostics from conditions.
2714//===----------------------------------------------------------------------===//
2715
2716/// Return the tag associated with this visitor. This tag will be used
2717/// to make all PathDiagnosticPieces created by this visitor.
2718const char *ConditionBRVisitor::getTag() { return "ConditionBRVisitor"; }
2719
2723 auto piece = VisitNodeImpl(N, BRC, BR);
2724 if (piece) {
2725 piece->setTag(getTag());
2726 if (auto *ev = dyn_cast<PathDiagnosticEventPiece>(piece.get()))
2727 ev->setPrunable(true, /* override */ false);
2728 }
2729 return piece;
2730}
2731
2734 BugReporterContext &BRC,
2736 ProgramPoint ProgPoint = N->getLocation();
2737 const std::pair<const ProgramPointTag *, const ProgramPointTag *> &Tags =
2739
2740 // If an assumption was made on a branch, it should be caught
2741 // here by looking at the state transition.
2742 if (std::optional<BlockEdge> BE = ProgPoint.getAs<BlockEdge>()) {
2743 const CFGBlock *SrcBlock = BE->getSrc();
2744 if (const Stmt *Term = SrcBlock->getTerminatorStmt()) {
2745 // If the tag of the previous node is 'Eagerly Assume...' the current
2746 // 'BlockEdge' has the same constraint information. We do not want to
2747 // report the value as it is just an assumption on the predecessor node
2748 // which will be caught in the next VisitNode() iteration as a 'PostStmt'.
2749 const ProgramPointTag *PreviousNodeTag =
2751 if (PreviousNodeTag == Tags.first || PreviousNodeTag == Tags.second)
2752 return nullptr;
2753
2754 return VisitTerminator(Term, N, SrcBlock, BE->getDst(), BR, BRC);
2755 }
2756 return nullptr;
2757 }
2758
2759 if (std::optional<PostStmt> PS = ProgPoint.getAs<PostStmt>()) {
2760 const ProgramPointTag *CurrentNodeTag = PS->getTag();
2761 if (CurrentNodeTag != Tags.first && CurrentNodeTag != Tags.second)
2762 return nullptr;
2763
2764 bool TookTrue = CurrentNodeTag == Tags.first;
2765 return VisitTrueTest(cast<Expr>(PS->getStmt()), BRC, BR, N, TookTrue);
2766 }
2767
2768 return nullptr;
2769}
2770
2772 const Stmt *Term, const ExplodedNode *N, const CFGBlock *srcBlk,
2773 const CFGBlock *dstBlk, PathSensitiveBugReport &R,
2774 BugReporterContext &BRC) {
2775 const Expr *Cond = nullptr;
2776
2777 // In the code below, Term is a CFG terminator and Cond is a branch condition
2778 // expression upon which the decision is made on this terminator.
2779 //
2780 // For example, in "if (x == 0)", the "if (x == 0)" statement is a terminator,
2781 // and "x == 0" is the respective condition.
2782 //
2783 // Another example: in "if (x && y)", we've got two terminators and two
2784 // conditions due to short-circuit nature of operator "&&":
2785 // 1. The "if (x && y)" statement is a terminator,
2786 // and "y" is the respective condition.
2787 // 2. Also "x && ..." is another terminator,
2788 // and "x" is its condition.
2789
2790 switch (Term->getStmtClass()) {
2791 // FIXME: Stmt::SwitchStmtClass is worth handling, however it is a bit
2792 // more tricky because there are more than two branches to account for.
2793 default:
2794 return nullptr;
2795 case Stmt::IfStmtClass: {
2796 const auto *IfStatement = cast<IfStmt>(Term);
2797 // Handle if consteval which doesn't have a traditional condition.
2798 if (IfStatement->isConsteval())
2799 return nullptr;
2800 Cond = IfStatement->getCond();
2801 break;
2802 }
2803 case Stmt::ConditionalOperatorClass:
2804 Cond = cast<ConditionalOperator>(Term)->getCond();
2805 break;
2806 case Stmt::BinaryOperatorClass:
2807 // When we encounter a logical operator (&& or ||) as a CFG terminator,
2808 // then the condition is actually its LHS; otherwise, we'd encounter
2809 // the parent, such as if-statement, as a terminator.
2810 const auto *BO = cast<BinaryOperator>(Term);
2811 assert(BO->isLogicalOp() &&
2812 "CFG terminator is not a short-circuit operator!");
2813 Cond = BO->getLHS();
2814 break;
2815 }
2816
2817 Cond = Cond->IgnoreParens();
2818
2819 // However, when we encounter a logical operator as a branch condition,
2820 // then the condition is actually its RHS, because LHS would be
2821 // the condition for the logical operator terminator.
2822 while (const auto *InnerBO = dyn_cast<BinaryOperator>(Cond)) {
2823 if (!InnerBO->isLogicalOp())
2824 break;
2825 Cond = InnerBO->getRHS()->IgnoreParens();
2826 }
2827
2828 assert(Cond);
2829 assert(srcBlk->succ_size() == 2);
2830 const bool TookTrue = *(srcBlk->succ_begin()) == dstBlk;
2831 return VisitTrueTest(Cond, BRC, R, N, TookTrue);
2832}
2833
2837 const ExplodedNode *N, bool TookTrue) {
2838 ProgramStateRef CurrentState = N->getState();
2839 ProgramStateRef PrevState = N->getFirstPred()->getState();
2840 const StackFrame *SF = N->getStackFrame();
2841
2842 // If the constraint information is changed between the current and the
2843 // previous program state we assuming the newly seen constraint information.
2844 // If we cannot evaluate the condition (and the constraints are the same)
2845 // the analyzer has no information about the value and just assuming it.
2846 // FIXME: This logic is not entirely correct, because e.g. in code like
2847 // void f(unsigned arg) {
2848 // if (arg >= 0) {
2849 // // ...
2850 // }
2851 // }
2852 // it will say that the "arg >= 0" check is _assuming_ something new because
2853 // the constraint that "$arg >= 0" is 1 was added to the list of known
2854 // constraints. However, the unsigned value is always >= 0 so semantically
2855 // this is not a "real" assumption.
2856 bool IsAssuming =
2857 !BRC.getStateManager().haveEqualConstraints(CurrentState, PrevState) ||
2858 CurrentState->getSVal(Cond, SF).isUnknownOrUndef();
2859
2860 // These will be modified in code below, but we need to preserve the original
2861 // values in case we want to throw the generic message.
2862 const Expr *CondTmp = Cond;
2863 bool TookTrueTmp = TookTrue;
2864
2865 while (true) {
2866 CondTmp = CondTmp->IgnoreParenCasts();
2867 switch (CondTmp->getStmtClass()) {
2868 default:
2869 break;
2870 case Stmt::BinaryOperatorClass:
2871 if (auto P = VisitTrueTest(Cond, cast<BinaryOperator>(CondTmp),
2872 BRC, R, N, TookTrueTmp, IsAssuming))
2873 return P;
2874 break;
2875 case Stmt::DeclRefExprClass:
2876 if (auto P = VisitTrueTest(Cond, cast<DeclRefExpr>(CondTmp),
2877 BRC, R, N, TookTrueTmp, IsAssuming))
2878 return P;
2879 break;
2880 case Stmt::MemberExprClass:
2881 if (auto P = VisitTrueTest(Cond, cast<MemberExpr>(CondTmp),
2882 BRC, R, N, TookTrueTmp, IsAssuming))
2883 return P;
2884 break;
2885 case Stmt::UnaryOperatorClass: {
2886 const auto *UO = cast<UnaryOperator>(CondTmp);
2887 if (UO->getOpcode() == UO_LNot) {
2888 TookTrueTmp = !TookTrueTmp;
2889 CondTmp = UO->getSubExpr();
2890 continue;
2891 }
2892 break;
2893 }
2894 }
2895 break;
2896 }
2897
2898 // Condition too complex to explain? Just say something so that the user
2899 // knew we've made some path decision at this point.
2900 // If it is too complex and we know the evaluation of the condition do not
2901 // repeat the note from 'BugReporter.cpp'
2902 if (!IsAssuming)
2903 return nullptr;
2904
2906 if (!Loc.isValid() || !Loc.asLocation().isValid())
2907 return nullptr;
2908
2909 return std::make_shared<PathDiagnosticEventPiece>(
2910 Loc, TookTrue ? GenericTrueMessage : GenericFalseMessage);
2911}
2912
2913bool ConditionBRVisitor::patternMatch(const Expr *Ex, const Expr *ParentEx,
2914 raw_ostream &Out, BugReporterContext &BRC,
2915 PathSensitiveBugReport &report,
2916 const ExplodedNode *N,
2917 std::optional<bool> &prunable,
2918 bool IsSameFieldName) {
2919 const Expr *OriginalExpr = Ex;
2920 Ex = Ex->IgnoreParenCasts();
2921
2923 FloatingLiteral>(Ex)) {
2924 // Use heuristics to determine if the expression is a macro
2925 // expanding to a literal and if so, use the macro's name.
2926 SourceLocation BeginLoc = OriginalExpr->getBeginLoc();
2927 SourceLocation EndLoc = OriginalExpr->getEndLoc();
2928 if (BeginLoc.isMacroID() && EndLoc.isMacroID()) {
2929 const SourceManager &SM = BRC.getSourceManager();
2930 const LangOptions &LO = BRC.getASTContext().getLangOpts();
2931 if (Lexer::isAtStartOfMacroExpansion(BeginLoc, SM, LO) &&
2932 Lexer::isAtEndOfMacroExpansion(EndLoc, SM, LO)) {
2933 CharSourceRange R = Lexer::getAsCharRange({BeginLoc, EndLoc}, SM, LO);
2934 Out << Lexer::getSourceText(R, SM, LO);
2935 return false;
2936 }
2937 }
2938 }
2939
2940 if (const auto *DR = dyn_cast<DeclRefExpr>(Ex)) {
2941 const bool quotes = isa<VarDecl>(DR->getDecl());
2942 if (quotes) {
2943 Out << '\'';
2944 const ProgramState *state = N->getState().get();
2945 if (const MemRegion *R =
2946 state->getLValue(cast<VarDecl>(DR->getDecl()), N->getStackFrame())
2947 .getAsRegion()) {
2948 if (report.isInteresting(R))
2949 prunable = false;
2950 else {
2951 const ProgramState *state = N->getState().get();
2952 SVal V = state->getSVal(R);
2953 if (report.isInteresting(V))
2954 prunable = false;
2955 }
2956 }
2957 }
2958 Out << DR->getDecl()->getDeclName().getAsString();
2959 if (quotes)
2960 Out << '\'';
2961 return quotes;
2962 }
2963
2964 if (const auto *IL = dyn_cast<IntegerLiteral>(Ex)) {
2965 QualType OriginalTy = OriginalExpr->getType();
2966 if (OriginalTy->isPointerType()) {
2967 if (IL->getValue() == 0) {
2968 Out << "null";
2969 return false;
2970 }
2971 }
2972 else if (OriginalTy->isObjCObjectPointerType()) {
2973 if (IL->getValue() == 0) {
2974 Out << "nil";
2975 return false;
2976 }
2977 }
2978
2979 Out << IL->getValue();
2980 return false;
2981 }
2982
2983 if (const auto *ME = dyn_cast<MemberExpr>(Ex)) {
2984 if (!IsSameFieldName)
2985 Out << "field '" << ME->getMemberDecl()->getName() << '\'';
2986 else
2987 Out << '\''
2991 nullptr)
2992 << '\'';
2993 }
2994
2995 return false;
2996}
2997
2999 const Expr *Cond, const BinaryOperator *BExpr, BugReporterContext &BRC,
3000 PathSensitiveBugReport &R, const ExplodedNode *N, bool TookTrue,
3001 bool IsAssuming) {
3002 bool shouldInvert = false;
3003 std::optional<bool> shouldPrune;
3004
3005 // Check if the field name of the MemberExprs is ambiguous. Example:
3006 // " 'a.d' is equal to 'h.d' " in 'test/Analysis/null-deref-path-notes.cpp'.
3007 bool IsSameFieldName = false;
3008 const auto *LhsME = dyn_cast<MemberExpr>(BExpr->getLHS()->IgnoreParenCasts());
3009 const auto *RhsME = dyn_cast<MemberExpr>(BExpr->getRHS()->IgnoreParenCasts());
3010
3011 if (LhsME && RhsME)
3012 IsSameFieldName =
3013 LhsME->getMemberDecl()->getName() == RhsME->getMemberDecl()->getName();
3014
3015 SmallString<128> LhsString, RhsString;
3016 {
3017 llvm::raw_svector_ostream OutLHS(LhsString), OutRHS(RhsString);
3018 const bool isVarLHS = patternMatch(BExpr->getLHS(), BExpr, OutLHS, BRC, R,
3019 N, shouldPrune, IsSameFieldName);
3020 const bool isVarRHS = patternMatch(BExpr->getRHS(), BExpr, OutRHS, BRC, R,
3021 N, shouldPrune, IsSameFieldName);
3022
3023 shouldInvert = !isVarLHS && isVarRHS;
3024 }
3025
3026 BinaryOperator::Opcode Op = BExpr->getOpcode();
3027
3029 // For assignment operators, all that we care about is that the LHS
3030 // evaluates to "true" or "false".
3031 return VisitConditionVariable(LhsString, BExpr->getLHS(), BRC, R, N,
3032 TookTrue);
3033 }
3034
3035 // For non-assignment operations, we require that we can understand
3036 // both the LHS and RHS.
3037 if (LhsString.empty() || RhsString.empty() ||
3038 !BinaryOperator::isComparisonOp(Op) || Op == BO_Cmp)
3039 return nullptr;
3040
3041 // Should we invert the strings if the LHS is not a variable name?
3042 SmallString<256> buf;
3043 llvm::raw_svector_ostream Out(buf);
3044 Out << (IsAssuming ? "Assuming " : "")
3045 << (shouldInvert ? RhsString : LhsString) << " is ";
3046
3047 // Do we need to invert the opcode?
3048 if (shouldInvert)
3049 switch (Op) {
3050 default: break;
3051 case BO_LT: Op = BO_GT; break;
3052 case BO_GT: Op = BO_LT; break;
3053 case BO_LE: Op = BO_GE; break;
3054 case BO_GE: Op = BO_LE; break;
3055 }
3056
3057 if (!TookTrue)
3058 switch (Op) {
3059 case BO_EQ: Op = BO_NE; break;
3060 case BO_NE: Op = BO_EQ; break;
3061 case BO_LT: Op = BO_GE; break;
3062 case BO_GT: Op = BO_LE; break;
3063 case BO_LE: Op = BO_GT; break;
3064 case BO_GE: Op = BO_LT; break;
3065 default:
3066 return nullptr;
3067 }
3068
3069 switch (Op) {
3070 case BO_EQ:
3071 Out << "equal to ";
3072 break;
3073 case BO_NE:
3074 Out << "not equal to ";
3075 break;
3076 default:
3077 Out << BinaryOperator::getOpcodeStr(Op) << ' ';
3078 break;
3079 }
3080
3081 Out << (shouldInvert ? LhsString : RhsString);
3082 const StackFrame *SF = N->getStackFrame();
3083 const SourceManager &SM = BRC.getSourceManager();
3084
3085 if (isVarAnInterestingCondition(BExpr->getLHS(), N, &R) ||
3086 isVarAnInterestingCondition(BExpr->getRHS(), N, &R))
3088
3089 // Convert 'field ...' to 'Field ...' if it is a MemberExpr.
3090 std::string Message = std::string(Out.str());
3091 Message[0] = toupper(Message[0]);
3092
3093 // If we know the value create a pop-up note to the value part of 'BExpr'.
3094 if (!IsAssuming) {
3096 if (!shouldInvert) {
3097 if (LhsME && LhsME->getMemberLoc().isValid())
3098 Loc = PathDiagnosticLocation(LhsME->getMemberLoc(), SM);
3099 else
3100 Loc = PathDiagnosticLocation(BExpr->getLHS(), SM, SF);
3101 } else {
3102 if (RhsME && RhsME->getMemberLoc().isValid())
3103 Loc = PathDiagnosticLocation(RhsME->getMemberLoc(), SM);
3104 else
3105 Loc = PathDiagnosticLocation(BExpr->getRHS(), SM, SF);
3106 }
3107
3108 return std::make_shared<PathDiagnosticPopUpPiece>(Loc, Message);
3109 }
3110
3112 auto event = std::make_shared<PathDiagnosticEventPiece>(Loc, Message);
3113 if (shouldPrune)
3114 event->setPrunable(*shouldPrune);
3115 return event;
3116}
3117
3119 StringRef LhsString, const Expr *CondVarExpr, BugReporterContext &BRC,
3120 PathSensitiveBugReport &report, const ExplodedNode *N, bool TookTrue) {
3121 // FIXME: If there's already a constraint tracker for this variable,
3122 // we shouldn't emit anything here (c.f. the double note in
3123 // test/Analysis/inlining/path-notes.c)
3124 SmallString<256> buf;
3125 llvm::raw_svector_ostream Out(buf);
3126 Out << "Assuming " << LhsString << " is ";
3127
3128 if (!printValue(CondVarExpr, Out, N, TookTrue, /*IsAssuming=*/true))
3129 return nullptr;
3130
3131 PathDiagnosticLocation Loc(CondVarExpr, BRC.getSourceManager(),
3132 N->getStackFrame());
3133
3134 if (isVarAnInterestingCondition(CondVarExpr, N, &report))
3136
3137 auto event = std::make_shared<PathDiagnosticEventPiece>(Loc, Out.str());
3138
3139 if (isInterestingExpr(CondVarExpr, N, &report))
3140 event->setPrunable(false);
3141
3142 return event;
3143}
3144
3146 const Expr *Cond, const DeclRefExpr *DRE, BugReporterContext &BRC,
3147 PathSensitiveBugReport &report, const ExplodedNode *N, bool TookTrue,
3148 bool IsAssuming) {
3149 const auto *VD = dyn_cast<VarDecl>(DRE->getDecl());
3150 if (!VD)
3151 return nullptr;
3152
3153 SmallString<256> Buf;
3154 llvm::raw_svector_ostream Out(Buf);
3155
3156 Out << (IsAssuming ? "Assuming '" : "'") << VD->getDeclName() << "' is ";
3157
3158 if (!printValue(DRE, Out, N, TookTrue, IsAssuming))
3159 return nullptr;
3160
3161 const StackFrame *SF = N->getStackFrame();
3162
3163 if (isVarAnInterestingCondition(DRE, N, &report))
3165
3166 // If we know the value create a pop-up note to the 'DRE'.
3167 if (!IsAssuming) {
3169 return std::make_shared<PathDiagnosticPopUpPiece>(Loc, Out.str());
3170 }
3171
3173 auto event = std::make_shared<PathDiagnosticEventPiece>(Loc, Out.str());
3174
3175 if (isInterestingExpr(DRE, N, &report))
3176 event->setPrunable(false);
3177
3178 return std::move(event);
3179}
3180
3182 const Expr *Cond, const MemberExpr *ME, BugReporterContext &BRC,
3183 PathSensitiveBugReport &report, const ExplodedNode *N, bool TookTrue,
3184 bool IsAssuming) {
3185 SmallString<256> Buf;
3186 llvm::raw_svector_ostream Out(Buf);
3187
3188 Out << (IsAssuming ? "Assuming field '" : "Field '")
3189 << ME->getMemberDecl()->getName() << "' is ";
3190
3191 if (!printValue(ME, Out, N, TookTrue, IsAssuming))
3192 return nullptr;
3193
3195
3196 // If we know the value create a pop-up note to the member of the MemberExpr.
3197 if (!IsAssuming && ME->getMemberLoc().isValid())
3199 else
3201 N->getStackFrame());
3202
3203 if (!Loc.isValid() || !Loc.asLocation().isValid())
3204 return nullptr;
3205
3206 if (isVarAnInterestingCondition(ME, N, &report))
3208
3209 // If we know the value create a pop-up note.
3210 if (!IsAssuming)
3211 return std::make_shared<PathDiagnosticPopUpPiece>(Loc, Out.str());
3212
3213 auto event = std::make_shared<PathDiagnosticEventPiece>(Loc, Out.str());
3214 if (isInterestingExpr(ME, N, &report))
3215 event->setPrunable(false);
3216 return event;
3217}
3218
3219bool ConditionBRVisitor::printValue(const Expr *CondVarExpr, raw_ostream &Out,
3220 const ExplodedNode *N, bool TookTrue,
3221 bool IsAssuming) {
3222 QualType Ty = CondVarExpr->getType();
3223
3224 if (Ty->isPointerType()) {
3225 Out << (TookTrue ? "non-null" : "null");
3226 return true;
3227 }
3228
3229 if (Ty->isObjCObjectPointerType()) {
3230 Out << (TookTrue ? "non-nil" : "nil");
3231 return true;
3232 }
3233
3234 if (!Ty->isIntegralOrEnumerationType())
3235 return false;
3236
3237 std::optional<const llvm::APSInt *> IntValue;
3238 if (!IsAssuming)
3239 IntValue = getConcreteIntegerValue(CondVarExpr, N);
3240
3241 if (IsAssuming || !IntValue) {
3242 if (Ty->isBooleanType())
3243 Out << (TookTrue ? "true" : "false");
3244 else
3245 Out << (TookTrue ? "not equal to 0" : "0");
3246 } else {
3247 if (Ty->isBooleanType())
3248 Out << ((*IntValue)->getBoolValue() ? "true" : "false");
3249 else
3250 Out << **IntValue;
3251 }
3252
3253 return true;
3254}
3255
3257 const PathDiagnosticPiece *Piece) {
3258 return Piece->getString() == GenericTrueMessage ||
3259 Piece->getString() == GenericFalseMessage;
3260}
3261
3262//===----------------------------------------------------------------------===//
3263// Implementation of LikelyFalsePositiveSuppressionBRVisitor.
3264//===----------------------------------------------------------------------===//
3265
3267 BugReporterContext &BRC, const ExplodedNode *N,
3269 // Here we suppress false positives coming from system headers. This list is
3270 // based on known issues.
3271 const AnalyzerOptions &Options = BRC.getAnalyzerOptions();
3272 const Decl *D = N->getStackFrame()->getDecl();
3273
3275 // Skip reports within the 'std' namespace. Although these can sometimes be
3276 // the user's fault, we currently don't report them very well, and
3277 // Note that this will not help for any other data structure libraries, like
3278 // TR1, Boost, or llvm/ADT.
3279 if (Options.ShouldSuppressFromCXXStandardLibrary) {
3280 BR.markInvalid(getTag(), nullptr);
3281 return;
3282 } else {
3283 // If the complete 'std' suppression is not enabled, suppress reports
3284 // from the 'std' namespace that are known to produce false positives.
3285
3286 // The analyzer issues a false use-after-free when std::list::pop_front
3287 // or std::list::pop_back are called multiple times because we cannot
3288 // reason about the internal invariants of the data structure.
3289 if (const auto *MD = dyn_cast<CXXMethodDecl>(D)) {
3290 const CXXRecordDecl *CD = MD->getParent();
3291 if (CD->getName() == "list") {
3292 BR.markInvalid(getTag(), nullptr);
3293 return;
3294 }
3295 }
3296
3297 // The analyzer issues a false positive when the constructor of
3298 // std::__independent_bits_engine from algorithms is used.
3299 if (const auto *MD = dyn_cast<CXXConstructorDecl>(D)) {
3300 const CXXRecordDecl *CD = MD->getParent();
3301 if (CD->getName() == "__independent_bits_engine") {
3302 BR.markInvalid(getTag(), nullptr);
3303 return;
3304 }
3305 }
3306
3307 for (const auto *SF = N->getStackFrame(); SF; SF = SF->getParent()) {
3308 const auto *MD = dyn_cast<CXXMethodDecl>(SF->getDecl());
3309 if (!MD)
3310 continue;
3311
3312 const CXXRecordDecl *CD = MD->getParent();
3313 // The analyzer issues a false positive on
3314 // std::basic_string<uint8_t> v; v.push_back(1);
3315 // and
3316 // std::u16string s; s += u'a';
3317 // because we cannot reason about the internal invariants of the
3318 // data structure.
3319 if (CD->getName() == "basic_string") {
3320 BR.markInvalid(getTag(), nullptr);
3321 return;
3322 }
3323
3324 // The analyzer issues a false positive on
3325 // std::shared_ptr<int> p(new int(1)); p = nullptr;
3326 // because it does not reason properly about temporary destructors.
3327 if (CD->getName() == "shared_ptr") {
3328 BR.markInvalid(getTag(), nullptr);
3329 return;
3330 }
3331 }
3332 }
3333 }
3334
3335 // Skip reports within the sys/queue.h macros as we do not have the ability to
3336 // reason about data structure shapes.
3337 const SourceManager &SM = BRC.getSourceManager();
3339 while (Loc.isMacroID()) {
3340 Loc = Loc.getSpellingLoc();
3341 if (SM.getFilename(Loc).ends_with("sys/queue.h")) {
3342 BR.markInvalid(getTag(), nullptr);
3343 return;
3344 }
3345 }
3346}
3347
3348//===----------------------------------------------------------------------===//
3349// Implementation of UndefOrNullArgVisitor.
3350//===----------------------------------------------------------------------===//
3351
3355 ProgramStateRef State = N->getState();
3356 ProgramPoint ProgLoc = N->getLocation();
3357
3358 // We are only interested in visiting CallEnter nodes.
3359 std::optional<CallEnter> CEnter = ProgLoc.getAs<CallEnter>();
3360 if (!CEnter)
3361 return nullptr;
3362
3363 // Check if one of the arguments is the region the visitor is tracking.
3365 CallEventRef<> Call = CEMgr.getCaller(CEnter->getCalleeStackFrame(), State);
3366 unsigned Idx = 0;
3367 ArrayRef<ParmVarDecl *> parms = Call->parameters();
3368
3369 for (const auto ParamDecl : parms) {
3370 const MemRegion *ArgReg = Call->getArgSVal(Idx).getAsRegion();
3371 ++Idx;
3372
3373 // Are we tracking the argument or its subregion?
3374 if ( !ArgReg || !R->isSubRegionOf(ArgReg->StripCasts()))
3375 continue;
3376
3377 // Check the function parameter type.
3378 assert(ParamDecl && "Formal parameter has no decl?");
3379 QualType T = ParamDecl->getType();
3380
3381 if (!(T->isAnyPointerType() || T->isReferenceType())) {
3382 // Function can only change the value passed in by address.
3383 continue;
3384 }
3385
3386 // If it is a const pointer value, the function does not intend to
3387 // change the value.
3388 if (T->getPointeeType().isConstQualified())
3389 continue;
3390
3391 // Mark the call site (StackFrame) as interesting if the value of the
3392 // argument is undefined or '0'/'NULL'.
3393 SVal BoundVal = State->getSVal(R);
3394 if (BoundVal.isUndef() || BoundVal.isZeroConstant()) {
3395 BR.markInteresting(CEnter->getCalleeStackFrame());
3396 return nullptr;
3397 }
3398 }
3399 return nullptr;
3400}
3401
3402//===----------------------------------------------------------------------===//
3403// Implementation of TagVisitor.
3404//===----------------------------------------------------------------------===//
3405
3406int NoteTag::Kind = 0;
3407
3408void TagVisitor::Profile(llvm::FoldingSetNodeID &ID) const {
3409 static int Tag = 0;
3410 ID.AddPointer(&Tag);
3411}
3412
3414 BugReporterContext &BRC,
3416 ProgramPoint PP = N->getLocation();
3417 const NoteTag *T = dyn_cast_or_null<NoteTag>(PP.getTag());
3418 if (!T)
3419 return nullptr;
3420
3421 if (std::optional<std::string> Msg = T->generateMessage(BRC, R)) {
3424 auto Piece = std::make_shared<PathDiagnosticEventPiece>(Loc, *Msg);
3425 Piece->setPrunable(T->isPrunable());
3426 return Piece;
3427 }
3428
3429 return nullptr;
3430}
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:229
const LangOptions & getLangOpts() const
Definition ASTContext.h:961
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:4041
Expr * getLHS() const
Definition Expr.h:4091
static bool isComparisonOp(Opcode Opc)
Definition Expr.h:4141
StringRef getOpcodeStr() const
Definition Expr.h:4107
Expr * getRHS() const
Definition Expr.h:4093
static bool isAdditiveOp(Opcode Opc)
Definition Expr.h:4127
static bool isAssignmentOp(Opcode Opc)
Definition Expr.h:4177
Opcode getOpcode() const
Definition Expr.h:4086
BinaryOperatorKind Opcode
Definition Expr.h:4046
Represents a single basic block in a source-level CFG.
Definition CFG.h:632
bool isInevitablySinking() const
Returns true if the block would eventually end with a sink (a noreturn node).
Definition CFG.cpp:6450
succ_iterator succ_begin()
Definition CFG.h:1017
Stmt * getTerminatorStmt()
Definition CFG.h:1114
const Stmt * getTerminatorCondition(bool StripParens=true) const
Definition CFG.cpp:6515
const Expr * getLastCondition() const
Definition CFG.cpp:6487
unsigned succ_size() const
Definition CFG.h:1035
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:1448
bool isLinear() const
Returns true if the CFG has no branches.
Definition CFG.cpp:5460
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:1273
ValueDecl * getDecl()
Definition Expr.h:1341
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:3102
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:3077
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:4926
Describes an C or C++ initializer list.
Definition Expr.h:5302
unsigned getNumInits() const
Definition Expr.h:5335
const Expr * getInit(unsigned Init) const
Definition Expr.h:5357
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:3367
SourceLocation getMemberLoc() const
getMemberLoc - Return the location of the "member", in X->F, it is the location of 'F'.
Definition Expr.h:3556
ValueDecl * getMemberDecl() const
Retrieve the member declaration to which this expression refers.
Definition Expr.h:3450
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:8497
bool isConstQualified() const
Determine whether this type is const-qualified.
Definition TypeBase.h:8518
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.
const Stmt * getStmt() const
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:9048
bool isBooleanType() const
Definition TypeBase.h:9185
RecordDecl * getAsRecordDecl() const
Retrieves the RecordDecl this type refers to.
Definition Type.h:41
bool isPointerType() const
Definition TypeBase.h:8682
bool isReferenceType() const
Definition TypeBase.h:8706
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:9170
bool isObjCObjectPointerType() const
Definition TypeBase.h:8861
const T * getAs() const
Member-template getAs<specific type>'.
Definition TypeBase.h:9275
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 isStaticLocal() const
Returns true if a variable with function scope is a static local variable.
Definition Decl.h:1206
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:259
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.