clang 20.0.0git
CheckerContext.cpp
Go to the documentation of this file.
1//== CheckerContext.cpp - Context info for path-sensitive checkers-----------=//
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 CheckerContext that provides contextual info for
10// path-sensitive checkers.
11//
12//===----------------------------------------------------------------------===//
13
16#include "clang/Lex/Lexer.h"
17#include "llvm/ADT/StringExtras.h"
18
19using namespace clang;
20using namespace ento;
21
23 const FunctionDecl *D = CE->getDirectCallee();
24 if (D)
25 return D;
26
27 const Expr *Callee = CE->getCallee();
28 SVal L = Pred->getSVal(Callee);
29 return L.getAsFunctionDecl();
30}
31
32StringRef CheckerContext::getCalleeName(const FunctionDecl *FunDecl) const {
33 if (!FunDecl)
34 return StringRef();
35 IdentifierInfo *funI = FunDecl->getIdentifier();
36 if (!funI)
37 return StringRef();
38 return funI->getName();
39}
40
42 if (isa<ObjCMethodDecl, CXXMethodDecl>(D))
43 return "method";
44 if (isa<BlockDecl>(D))
45 return "anonymous block";
46 return "function";
47}
48
50 StringRef Name) {
51 // To avoid false positives (Ex: finding user defined functions with
52 // similar names), only perform fuzzy name matching when it's a builtin.
53 // Using a string compare is slow, we might want to switch on BuiltinID here.
54 unsigned BId = FD->getBuiltinID();
55 if (BId != 0) {
56 if (Name.empty())
57 return true;
58 StringRef BName = FD->getASTContext().BuiltinInfo.getName(BId);
59 size_t start = BName.find(Name);
60 if (start != StringRef::npos) {
61 // Accept exact match.
62 if (BName.size() == Name.size())
63 return true;
64
65 // v-- match starts here
66 // ...xxxxx...
67 // _xxxxx_
68 // ^ ^ lookbehind and lookahead characters
69
70 const auto MatchPredecessor = [=]() -> bool {
71 return start <= 0 || !llvm::isAlpha(BName[start - 1]);
72 };
73 const auto MatchSuccessor = [=]() -> bool {
74 std::size_t LookbehindPlace = start + Name.size();
75 return LookbehindPlace >= BName.size() ||
76 !llvm::isAlpha(BName[LookbehindPlace]);
77 };
78
79 if (MatchPredecessor() && MatchSuccessor())
80 return true;
81 }
82 }
83
84 const IdentifierInfo *II = FD->getIdentifier();
85 // If this is a special C++ name without IdentifierInfo, it can't be a
86 // C library function.
87 if (!II)
88 return false;
89
90 // C library functions are either declared directly within a TU (the common
91 // case) or they are accessed through the namespace `std` (when they are used
92 // in C++ via headers like <cstdlib>).
93 const DeclContext *DC = FD->getDeclContext()->getRedeclContext();
94 if (!(DC->isTranslationUnit() || DC->isStdNamespace()))
95 return false;
96
97 // If this function is not externally visible, it is not a C library function.
98 // Note that we make an exception for inline functions, which may be
99 // declared in header files without external linkage.
100 if (!FD->isInlined() && !FD->isExternallyVisible())
101 return false;
102
103 if (Name.empty())
104 return true;
105
106 StringRef FName = II->getName();
107 if (FName == Name)
108 return true;
109
110 if (FName.starts_with("__inline") && FName.contains(Name))
111 return true;
112
113 return false;
114}
115
117 StringRef Name) {
118 const IdentifierInfo *II = FD->getIdentifier();
119 if (!II)
120 return false;
121
122 auto CompletelyMatchesParts = [II](auto... Parts) -> bool {
123 StringRef FName = II->getName();
124 return (FName.consume_front(Parts) && ...) && FName.empty();
125 };
126
127 return CompletelyMatchesParts("__", Name, "_chk") ||
128 CompletelyMatchesParts("__builtin_", "__", Name, "_chk");
129}
130
132 if (Loc.isMacroID())
134 getLangOpts());
135 SmallString<16> buf;
137}
138
139/// Evaluate comparison and return true if it's known that condition is true
140static bool evalComparison(SVal LHSVal, BinaryOperatorKind ComparisonOp,
141 SVal RHSVal, ProgramStateRef State) {
142 if (LHSVal.isUnknownOrUndef())
143 return false;
144 ProgramStateManager &Mgr = State->getStateManager();
145 if (!isa<NonLoc>(LHSVal)) {
146 LHSVal = Mgr.getStoreManager().getBinding(State->getStore(),
147 LHSVal.castAs<Loc>());
148 if (LHSVal.isUnknownOrUndef() || !isa<NonLoc>(LHSVal))
149 return false;
150 }
151
152 SValBuilder &Bldr = Mgr.getSValBuilder();
153 SVal Eval = Bldr.evalBinOp(State, ComparisonOp, LHSVal, RHSVal,
154 Bldr.getConditionType());
155 if (Eval.isUnknownOrUndef())
156 return false;
157 ProgramStateRef StTrue, StFalse;
158 std::tie(StTrue, StFalse) = State->assume(Eval.castAs<DefinedSVal>());
159 return StTrue && !StFalse;
160}
161
162bool CheckerContext::isGreaterOrEqual(const Expr *E, unsigned long long Val) {
163 DefinedSVal V = getSValBuilder().makeIntVal(Val, getASTContext().LongLongTy);
164 return evalComparison(getSVal(E), BO_GE, V, getState());
165}
166
169 return evalComparison(getSVal(E), BO_LT, V, getState());
170}
#define V(N, I)
Definition: ASTContext.h:3341
Defines enum values for all the target-independent builtin functions.
const Decl * D
Expr * E
static bool evalComparison(SVal LHSVal, BinaryOperatorKind ComparisonOp, SVal RHSVal, ProgramStateRef State)
Evaluate comparison and return true if it's known that condition is true.
Builtin::Context & BuiltinInfo
Definition: ASTContext.h:662
llvm::StringRef getName(unsigned ID) const
Return the identifier name for the specified builtin, e.g.
Definition: Builtins.h:103
CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
Definition: Expr.h:2830
FunctionDecl * getDirectCallee()
If the callee is a FunctionDecl, return it. Otherwise return null.
Definition: Expr.h:3000
Expr * getCallee()
Definition: Expr.h:2980
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
Definition: DeclBase.h:1436
bool isTranslationUnit() const
Definition: DeclBase.h:2166
DeclContext * getRedeclContext()
getRedeclContext - Retrieve the context in which an entity conflicts with other entities of the same ...
Definition: DeclBase.cpp:1988
bool isStdNamespace() const
Definition: DeclBase.cpp:1317
Decl - This represents one declaration (or definition), e.g.
Definition: DeclBase.h:86
ASTContext & getASTContext() const LLVM_READONLY
Definition: DeclBase.cpp:523
DeclContext * getDeclContext()
Definition: DeclBase.h:455
This represents one expression.
Definition: Expr.h:110
Represents a function declaration or definition.
Definition: Decl.h:1932
unsigned getBuiltinID(bool ConsiderWrapperFunctions=false) const
Returns a value indicating whether this function corresponds to a builtin function.
Definition: Decl.cpp:3618
bool isInlined() const
Determine whether this function should be inlined, because it is either marked "inline" or "constexpr...
Definition: Decl.h:2793
One of these records is kept for each identifier that is lexed.
StringRef getName() const
Return the actual identifier string.
static StringRef getImmediateMacroName(SourceLocation Loc, const SourceManager &SM, const LangOptions &LangOpts)
Retrieve the name of the immediate macro expansion.
Definition: Lexer.cpp:1060
static unsigned getSpelling(const Token &Tok, const char *&Buffer, const SourceManager &SourceMgr, const LangOptions &LangOpts, bool *Invalid=nullptr)
getSpelling - This method is used to get the spelling of a token into a preallocated buffer,...
Definition: Lexer.cpp:452
IdentifierInfo * getIdentifier() const
Get the identifier that names this declaration, if there is one.
Definition: Decl.h:270
bool isExternallyVisible() const
Definition: Decl.h:408
Encodes a location in the source.
StringRef getDeclDescription(const Decl *D)
Returns the word that should be used to refer to the declaration in the report.
const SourceManager & getSourceManager()
SValBuilder & getSValBuilder()
StringRef getCalleeName(const FunctionDecl *FunDecl) const
Get the name of the called function (path-sensitive).
const ProgramStateRef & getState() const
SVal getSVal(const Stmt *S) const
Get the value of arbitrary expressions at this point in the path.
bool isNegative(const Expr *E)
Returns true if the value of E is negative.
bool isGreaterOrEqual(const Expr *E, unsigned long long Val)
Returns true if the value of E is greater than or equal to Val under unsigned comparison.
static bool isCLibraryFunction(const FunctionDecl *FD, StringRef Name=StringRef())
Returns true if the given function is an externally-visible function in the top-level namespace,...
const FunctionDecl * getCalleeDecl(const CallExpr *CE) const
Get the declaration of the called function (path-sensitive).
StringRef getMacroNameOrSpelling(SourceLocation &Loc)
Depending on wither the location corresponds to a macro, return either the macro name or the token sp...
const LangOptions & getLangOpts() const
static bool isHardenedVariantOf(const FunctionDecl *FD, StringRef Name)
In builds that use source hardening (-D_FORTIFY_SOURCE), many standard functions are implemented as m...
SVal getSVal(const Stmt *S) const
Get the value of an arbitrary expression at this node.
nonloc::ConcreteInt makeIntVal(const IntegerLiteral *integer)
Definition: SValBuilder.h:290
QualType getConditionType() const
Definition: SValBuilder.h:153
SVal evalBinOp(ProgramStateRef state, BinaryOperator::Opcode op, SVal lhs, SVal rhs, QualType type)
SVal - This represents a symbolic expression, which can be either an L-value or an R-value.
Definition: SVals.h:55
bool isUnknownOrUndef() const
Definition: SVals.h:106
const FunctionDecl * getAsFunctionDecl() const
getAsFunctionDecl - If this SVal is a MemRegionVal and wraps a CodeTextRegion wrapping a FunctionDecl...
Definition: SVals.cpp:46
T castAs() const
Convert to the specified SVal type, asserting that this SVal is of the desired type.
Definition: SVals.h:82
virtual SVal getBinding(Store store, Loc loc, QualType T=QualType())=0
Return the value bound to specified location in a given state.
The JSON file list parser is used to communicate input to InstallAPI.
BinaryOperatorKind