clang 22.0.0git
BuiltinFunctionChecker.cpp
Go to the documentation of this file.
1//=== BuiltinFunctionChecker.cpp --------------------------------*- C++ -*-===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This checker evaluates "standalone" clang builtin functions that are not
10// just special-cased variants of well-known non-builtin functions.
11// Builtin functions like __builtin_memcpy and __builtin_alloca should be
12// evaluated by the same checker that handles their non-builtin variant to
13// ensure that the two variants are handled consistently.
14//
15//===----------------------------------------------------------------------===//
16
27
28using namespace clang;
29using namespace ento;
30using namespace taint;
31
32namespace {
33
34QualType getSufficientTypeForOverflowOp(CheckerContext &C, const QualType &T) {
35 // Calling a builtin with a non-integer type result produces compiler error.
36 assert(T->isIntegerType());
37
38 ASTContext &ACtx = C.getASTContext();
39 unsigned BitWidth = ACtx.getIntWidth(T);
40 return ACtx.getBitIntType(T->isUnsignedIntegerType(), BitWidth * 2);
41}
42
43QualType getOverflowBuiltinResultType(const CallEvent &Call) {
44 // Calling a builtin with an incorrect argument count produces compiler error.
45 assert(Call.getNumArgs() == 3);
46
47 return Call.getArgExpr(2)->getType()->getPointeeType();
48}
49
50QualType getOverflowBuiltinResultType(const CallEvent &Call, CheckerContext &C,
51 unsigned BI) {
52 // Calling a builtin with an incorrect argument count produces compiler error.
53 assert(Call.getNumArgs() == 3);
54
55 ASTContext &ACtx = C.getASTContext();
56
57 switch (BI) {
58 case Builtin::BI__builtin_smul_overflow:
59 case Builtin::BI__builtin_ssub_overflow:
60 case Builtin::BI__builtin_sadd_overflow:
61 return ACtx.IntTy;
62 case Builtin::BI__builtin_smull_overflow:
63 case Builtin::BI__builtin_ssubl_overflow:
64 case Builtin::BI__builtin_saddl_overflow:
65 return ACtx.LongTy;
66 case Builtin::BI__builtin_smulll_overflow:
67 case Builtin::BI__builtin_ssubll_overflow:
68 case Builtin::BI__builtin_saddll_overflow:
69 return ACtx.LongLongTy;
70 case Builtin::BI__builtin_umul_overflow:
71 case Builtin::BI__builtin_usub_overflow:
72 case Builtin::BI__builtin_uadd_overflow:
73 return ACtx.UnsignedIntTy;
74 case Builtin::BI__builtin_umull_overflow:
75 case Builtin::BI__builtin_usubl_overflow:
76 case Builtin::BI__builtin_uaddl_overflow:
77 return ACtx.UnsignedLongTy;
78 case Builtin::BI__builtin_umulll_overflow:
79 case Builtin::BI__builtin_usubll_overflow:
80 case Builtin::BI__builtin_uaddll_overflow:
81 return ACtx.UnsignedLongLongTy;
82 case Builtin::BI__builtin_mul_overflow:
83 case Builtin::BI__builtin_sub_overflow:
84 case Builtin::BI__builtin_add_overflow:
85 return getOverflowBuiltinResultType(Call);
86 default:
87 assert(false && "Unknown overflow builtin");
88 return ACtx.IntTy;
89 }
90}
91
92class BuiltinFunctionChecker : public Checker<eval::Call> {
93public:
94 bool evalCall(const CallEvent &Call, CheckerContext &C) const;
95 void handleOverflowBuiltin(const CallEvent &Call, CheckerContext &C,
97 QualType ResultType) const;
98 const NoteTag *createBuiltinOverflowNoteTag(CheckerContext &C,
99 bool BothFeasible, SVal Arg1,
100 SVal Arg2, SVal Result) const;
101 ProgramStateRef initStateAftetBuiltinOverflow(CheckerContext &C,
102 ProgramStateRef State,
103 const CallEvent &Call,
104 SVal RetCal,
105 bool IsOverflow) const;
106 std::pair<bool, bool> checkOverflow(CheckerContext &C, SVal RetVal,
107 QualType Res) const;
108
109private:
110 // From: clang/include/clang/Basic/Builtins.def
111 // C++ standard library builtins in namespace 'std'.
112 const CallDescriptionSet BuiltinLikeStdFunctions{
113 {CDM::SimpleFunc, {"std", "addressof"}}, //
114 {CDM::SimpleFunc, {"std", "__addressof"}}, //
115 {CDM::SimpleFunc, {"std", "as_const"}}, //
116 {CDM::SimpleFunc, {"std", "forward"}}, //
117 {CDM::SimpleFunc, {"std", "forward_like"}}, //
118 {CDM::SimpleFunc, {"std", "move"}}, //
119 {CDM::SimpleFunc, {"std", "move_if_noexcept"}}, //
120 };
121
122 bool isBuiltinLikeFunction(const CallEvent &Call) const;
123};
124
125} // namespace
126
127const NoteTag *BuiltinFunctionChecker::createBuiltinOverflowNoteTag(
128 CheckerContext &C, bool overflow, SVal Arg1, SVal Arg2, SVal Result) const {
129 return C.getNoteTag([Result, Arg1, Arg2, overflow](PathSensitiveBugReport &BR,
130 llvm::raw_ostream &OS) {
131 if (!BR.isInteresting(Result))
132 return;
133
134 // Propagate interestingness to input arguments if result is interesting.
135 BR.markInteresting(Arg1);
136 BR.markInteresting(Arg2);
137
138 if (overflow)
139 OS << "Assuming overflow";
140 else
141 OS << "Assuming no overflow";
142 });
143}
144
145std::pair<bool, bool>
146BuiltinFunctionChecker::checkOverflow(CheckerContext &C, SVal RetVal,
147 QualType Res) const {
148 // Calling a builtin with a non-integer type result produces compiler error.
149 assert(Res->isIntegerType());
150
151 unsigned BitWidth = C.getASTContext().getIntWidth(Res);
152 bool IsUnsigned = Res->isUnsignedIntegerType();
153
154 SValBuilder &SVB = C.getSValBuilder();
155 BasicValueFactory &VF = SVB.getBasicValueFactory();
156
157 auto MinValType = llvm::APSInt::getMinValue(BitWidth, IsUnsigned);
158 auto MaxValType = llvm::APSInt::getMaxValue(BitWidth, IsUnsigned);
159 nonloc::ConcreteInt MinVal{VF.getValue(MinValType)};
160 nonloc::ConcreteInt MaxVal{VF.getValue(MaxValType)};
161
162 ProgramStateRef State = C.getState();
163 SVal IsLeMax = SVB.evalBinOp(State, BO_LE, RetVal, MaxVal, Res);
164 SVal IsGeMin = SVB.evalBinOp(State, BO_GE, RetVal, MinVal, Res);
165
166 auto [MayNotOverflow, MayOverflow] =
167 State->assume(IsLeMax.castAs<DefinedOrUnknownSVal>());
168 auto [MayNotUnderflow, MayUnderflow] =
169 State->assume(IsGeMin.castAs<DefinedOrUnknownSVal>());
170
171 return {MayOverflow || MayUnderflow, MayNotOverflow && MayNotUnderflow};
172}
173
174ProgramStateRef BuiltinFunctionChecker::initStateAftetBuiltinOverflow(
175 CheckerContext &C, ProgramStateRef State, const CallEvent &Call,
176 SVal RetVal, bool IsOverflow) const {
177 SValBuilder &SVB = C.getSValBuilder();
178 SVal Arg1 = Call.getArgSVal(0);
179 SVal Arg2 = Call.getArgSVal(1);
180 auto BoolTy = C.getASTContext().BoolTy;
181
182 ProgramStateRef NewState =
183 State->BindExpr(Call.getOriginExpr(), C.getLocationContext(),
184 SVB.makeTruthVal(IsOverflow, BoolTy));
185
186 if (auto L = Call.getArgSVal(2).getAs<Loc>()) {
187 NewState = NewState->bindLoc(*L, RetVal, C.getLocationContext());
188
189 // Propagate taint if any of the arguments were tainted
190 if (isTainted(State, Arg1) || isTainted(State, Arg2))
191 NewState = addTaint(NewState, *L);
192 }
193
194 return NewState;
195}
196
197void BuiltinFunctionChecker::handleOverflowBuiltin(const CallEvent &Call,
198 CheckerContext &C,
200 QualType ResultType) const {
201 // Calling a builtin with an incorrect argument count produces compiler error.
202 assert(Call.getNumArgs() == 3);
203
204 ProgramStateRef State = C.getState();
205 SValBuilder &SVB = C.getSValBuilder();
206
207 SVal Arg1 = Call.getArgSVal(0);
208 SVal Arg2 = Call.getArgSVal(1);
209
210 QualType SufficientlyWideTy = getSufficientTypeForOverflowOp(C, ResultType);
211 assert(!SufficientlyWideTy.isNull());
212
213 SVal RetValMax = SVB.evalBinOp(State, Op, Arg1, Arg2, SufficientlyWideTy);
214 SVal RetVal = SVB.evalBinOp(State, Op, Arg1, Arg2, ResultType);
215
216 auto [Overflow, NotOverflow] = checkOverflow(C, RetValMax, ResultType);
217
218 if (NotOverflow) {
219 auto NewState =
220 initStateAftetBuiltinOverflow(C, State, Call, RetVal, false);
221
222 C.addTransition(NewState, createBuiltinOverflowNoteTag(
223 C, /*overflow=*/false, Arg1, Arg2, RetVal));
224 }
225
226 if (Overflow) {
227 auto NewState = initStateAftetBuiltinOverflow(C, State, Call, RetVal, true);
228
229 C.addTransition(NewState, createBuiltinOverflowNoteTag(C, /*overflow=*/true,
230 Arg1, Arg2, RetVal));
231 }
232}
233
234bool BuiltinFunctionChecker::isBuiltinLikeFunction(
235 const CallEvent &Call) const {
236 const auto *FD = llvm::dyn_cast_or_null<FunctionDecl>(Call.getDecl());
237 if (!FD || FD->getNumParams() != 1)
238 return false;
239
240 if (QualType RetTy = FD->getReturnType();
241 !RetTy->isPointerType() && !RetTy->isReferenceType())
242 return false;
243
244 if (QualType ParmTy = FD->getParamDecl(0)->getType();
245 !ParmTy->isPointerType() && !ParmTy->isReferenceType())
246 return false;
247
248 return BuiltinLikeStdFunctions.contains(Call);
249}
250
251bool BuiltinFunctionChecker::evalCall(const CallEvent &Call,
252 CheckerContext &C) const {
253 ProgramStateRef state = C.getState();
254 const auto *FD = dyn_cast_or_null<FunctionDecl>(Call.getDecl());
255 if (!FD)
256 return false;
257
258 const LocationContext *LCtx = C.getLocationContext();
259 const Expr *CE = Call.getOriginExpr();
260
261 if (isBuiltinLikeFunction(Call)) {
262 C.addTransition(state->BindExpr(CE, LCtx, Call.getArgSVal(0)));
263 return true;
264 }
265
266 unsigned BI = FD->getBuiltinID();
267
268 switch (BI) {
269 default:
270 return false;
271 case Builtin::BI__builtin_mul_overflow:
272 case Builtin::BI__builtin_smul_overflow:
273 case Builtin::BI__builtin_smull_overflow:
274 case Builtin::BI__builtin_smulll_overflow:
275 case Builtin::BI__builtin_umul_overflow:
276 case Builtin::BI__builtin_umull_overflow:
277 case Builtin::BI__builtin_umulll_overflow:
278 handleOverflowBuiltin(Call, C, BO_Mul,
279 getOverflowBuiltinResultType(Call, C, BI));
280 return true;
281 case Builtin::BI__builtin_sub_overflow:
282 case Builtin::BI__builtin_ssub_overflow:
283 case Builtin::BI__builtin_ssubl_overflow:
284 case Builtin::BI__builtin_ssubll_overflow:
285 case Builtin::BI__builtin_usub_overflow:
286 case Builtin::BI__builtin_usubl_overflow:
287 case Builtin::BI__builtin_usubll_overflow:
288 handleOverflowBuiltin(Call, C, BO_Sub,
289 getOverflowBuiltinResultType(Call, C, BI));
290 return true;
291 case Builtin::BI__builtin_add_overflow:
292 case Builtin::BI__builtin_sadd_overflow:
293 case Builtin::BI__builtin_saddl_overflow:
294 case Builtin::BI__builtin_saddll_overflow:
295 case Builtin::BI__builtin_uadd_overflow:
296 case Builtin::BI__builtin_uaddl_overflow:
297 case Builtin::BI__builtin_uaddll_overflow:
298 handleOverflowBuiltin(Call, C, BO_Add,
299 getOverflowBuiltinResultType(Call, C, BI));
300 return true;
301 case Builtin::BI__builtin_unpredictable:
302 case Builtin::BI__builtin_expect:
303 case Builtin::BI__builtin_expect_with_probability:
304 case Builtin::BI__builtin_assume_aligned:
305 case Builtin::BI__builtin_addressof:
306 case Builtin::BI__builtin_function_start: {
307 // For __builtin_unpredictable, __builtin_expect,
308 // __builtin_expect_with_probability and __builtin_assume_aligned,
309 // just return the value of the subexpression.
310 // __builtin_addressof is going from a reference to a pointer, but those
311 // are represented the same way in the analyzer.
312 assert (Call.getNumArgs() > 0);
313 SVal Arg = Call.getArgSVal(0);
314 C.addTransition(state->BindExpr(CE, LCtx, Arg));
315 return true;
316 }
317
318 case Builtin::BI__builtin_dynamic_object_size:
319 case Builtin::BI__builtin_object_size:
320 case Builtin::BI__builtin_constant_p: {
321 // This must be resolvable at compile time, so we defer to the constant
322 // evaluator for a value.
323 SValBuilder &SVB = C.getSValBuilder();
324 SVal V = UnknownVal();
325 Expr::EvalResult EVResult;
326 if (CE->EvaluateAsInt(EVResult, C.getASTContext(), Expr::SE_NoSideEffects)) {
327 // Make sure the result has the correct type.
328 llvm::APSInt Result = EVResult.Val.getInt();
329 BasicValueFactory &BVF = SVB.getBasicValueFactory();
330 BVF.getAPSIntType(CE->getType()).apply(Result);
331 V = SVB.makeIntVal(Result);
332 }
333
334 if (FD->getBuiltinID() == Builtin::BI__builtin_constant_p) {
335 // If we didn't manage to figure out if the value is constant or not,
336 // it is safe to assume that it's not constant and unsafe to assume
337 // that it's constant.
338 if (V.isUnknown())
339 V = SVB.makeIntVal(0, CE->getType());
340 }
341
342 C.addTransition(state->BindExpr(CE, LCtx, V));
343 return true;
344 }
345 }
346}
347
348void ento::registerBuiltinFunctionChecker(CheckerManager &mgr) {
349 mgr.registerChecker<BuiltinFunctionChecker>();
350}
351
352bool ento::shouldRegisterBuiltinFunctionChecker(const CheckerManager &mgr) {
353 return true;
354}
#define V(N, I)
Defines enum values for all the target-independent builtin functions.
APSInt & getInt()
Definition APValue.h:489
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition ASTContext.h:220
CanQualType LongTy
unsigned getIntWidth(QualType T) const
CanQualType UnsignedLongTy
CanQualType IntTy
CanQualType UnsignedIntTy
CanQualType UnsignedLongLongTy
CanQualType LongLongTy
QualType getBitIntType(bool Unsigned, unsigned NumBits) const
Return a bit-precise integer type with the specified signedness and bit count.
BinaryOperatorKind Opcode
Definition Expr.h:4043
bool EvaluateAsInt(EvalResult &Result, const ASTContext &Ctx, SideEffectsKind AllowSideEffects=SE_NoSideEffects, bool InConstantContext=false) const
EvaluateAsInt - Return true if this is a constant which we can fold and convert to an integer,...
@ SE_NoSideEffects
Strictly evaluate the expression.
Definition Expr.h:671
QualType getType() const
Definition Expr.h:144
A (possibly-)qualified type.
Definition TypeBase.h:937
bool isNull() const
Return true if this QualType doesn't point to a type yet.
Definition TypeBase.h:1004
bool isIntegerType() const
isIntegerType() does not include complex integers (a GCC extension).
Definition TypeBase.h:8935
bool isUnsignedIntegerType() const
Return true if this is an integer type that is unsigned, according to C99 6.2.5p6 [which returns true...
Definition Type.cpp:2254
void apply(llvm::APSInt &Value) const
Convert a given APSInt, in place, to match this type.
Definition APSIntType.h:37
APSIntType getAPSIntType(QualType T) const
Returns the type of the APSInt used to store values of the given QualType.
bool contains(const CallEvent &Call) const
Represents an abstract call to a function or method along a particular path.
Definition CallEvent.h:153
CHECKER * registerChecker(AT &&...Args)
Register a single-part checker (derived from Checker): construct its singleton instance,...
Simple checker classes that implement one frontend (i.e.
Definition Checker.h:553
The tag upon which the TagVisitor reacts.
void markInteresting(SymbolRef sym, bugreporter::TrackingKind TKind=bugreporter::TrackingKind::Thorough)
Marks a symbol as interesting.
bool isInteresting(SymbolRef sym) const
BasicValueFactory & getBasicValueFactory()
nonloc::ConcreteInt makeIntVal(const IntegerLiteral *integer)
nonloc::ConcreteInt makeTruthVal(bool b, QualType type)
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:56
T castAs() const
Convert to the specified SVal type, asserting that this SVal is of the desired type.
Definition SVals.h:83
ProgramStateRef addTaint(ProgramStateRef State, const Stmt *S, const LocationContext *LCtx, TaintTagType Kind=TaintTagGeneric)
Create a new state in which the value of the statement is marked as tainted.
Definition Taint.cpp:46
bool isTainted(ProgramStateRef State, const Stmt *S, const LocationContext *LCtx, TaintTagType Kind=TaintTagGeneric)
Check if the statement has a tainted value in the given state.
Definition Taint.cpp:148
IntrusiveRefCntPtr< const ProgramState > ProgramStateRef
@ OS
Indicates that the tracking object is a descendant of a referenced-counted OSObject,...
The JSON file list parser is used to communicate input to InstallAPI.
@ Result
The result type of a method or function.
Definition TypeBase.h:905
const FunctionProtoType * T
APValue Val
Val - This is the value the expression can be folded to.
Definition Expr.h:647