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