clang 24.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#include <algorithm>
28
29using namespace clang;
30using namespace ento;
31using namespace taint;
32
33namespace {
34
35/// \return an integer type that is large enough for the binary operation on the
36/// operands of \p Arg1Ty and \p Arg2Ty, respectively.
37QualType getSufficientTypeForOverflowOp(CheckerContext &C,
39 QualType Arg1Ty, QualType Arg2Ty) {
40 assert(Arg1Ty->isIntegerType() && Arg2Ty->isIntegerType());
41
42 ASTContext &ACtx = C.getASTContext();
43 unsigned BitWidth =
44 std::max(ACtx.getIntWidth(Arg1Ty), ACtx.getIntWidth(Arg2Ty));
45
46 // A signed type with doubled bits may not be large enough to hold the
47 // multiplication result when both operands are unsigned. In other
48 // words, if either operand is signed, a signed type with twice the bits is
49 // sufficient.
50 //
51 // Additionally, subtraction always needs a signed result. Note that
52 // subtracting a negative operand falls into the prior case, so it is still
53 // safe with a signed result type. A signed 1-bit integer is not allowed in
54 // Clang.
55 bool UseSigned = Op == BO_Sub || Arg1Ty->isSignedIntegerType() ||
56 Arg2Ty->isSignedIntegerType();
57 return ACtx.getBitIntType(/*Unsigned=*/!UseSigned, BitWidth * 2);
58}
59
60QualType getOverflowBuiltinResultType(const CallEvent &Call) {
61 // Calling a builtin with an incorrect argument count produces compiler error.
62 assert(Call.getNumArgs() == 3);
63
64 return Call.getArgExpr(2)->getType()->getPointeeType();
65}
66
67QualType getOverflowBuiltinResultType(const CallEvent &Call, CheckerContext &C,
68 unsigned BI) {
69 // Calling a builtin with an incorrect argument count produces compiler error.
70 assert(Call.getNumArgs() == 3);
71
72 ASTContext &ACtx = C.getASTContext();
73
74 switch (BI) {
75 case Builtin::BI__builtin_smul_overflow:
76 case Builtin::BI__builtin_ssub_overflow:
77 case Builtin::BI__builtin_sadd_overflow:
78 return ACtx.IntTy;
79 case Builtin::BI__builtin_smull_overflow:
80 case Builtin::BI__builtin_ssubl_overflow:
81 case Builtin::BI__builtin_saddl_overflow:
82 return ACtx.LongTy;
83 case Builtin::BI__builtin_smulll_overflow:
84 case Builtin::BI__builtin_ssubll_overflow:
85 case Builtin::BI__builtin_saddll_overflow:
86 return ACtx.LongLongTy;
87 case Builtin::BI__builtin_umul_overflow:
88 case Builtin::BI__builtin_usub_overflow:
89 case Builtin::BI__builtin_uadd_overflow:
90 return ACtx.UnsignedIntTy;
91 case Builtin::BI__builtin_umull_overflow:
92 case Builtin::BI__builtin_usubl_overflow:
93 case Builtin::BI__builtin_uaddl_overflow:
94 return ACtx.UnsignedLongTy;
95 case Builtin::BI__builtin_umulll_overflow:
96 case Builtin::BI__builtin_usubll_overflow:
97 case Builtin::BI__builtin_uaddll_overflow:
98 return ACtx.UnsignedLongLongTy;
99 case Builtin::BI__builtin_mul_overflow:
100 case Builtin::BI__builtin_sub_overflow:
101 case Builtin::BI__builtin_add_overflow:
102 return getOverflowBuiltinResultType(Call);
103 default:
104 assert(false && "Unknown overflow builtin");
105 return ACtx.IntTy;
106 }
107}
108
109class BuiltinFunctionChecker : public Checker<eval::Call> {
110public:
111 bool evalCall(const CallEvent &Call, CheckerContext &C) const;
112 void handleOverflowBuiltin(const CallEvent &Call, CheckerContext &C,
114 QualType ResultType) const;
115 const NoteTag *createBuiltinOverflowNoteTag(CheckerContext &C,
116 bool BothFeasible, SVal Arg1,
117 SVal Arg2, SVal Result) const;
118 ProgramStateRef initStateAftetBuiltinOverflow(CheckerContext &C,
119 ProgramStateRef State,
120 const CallEvent &Call,
121 SVal RetCal,
122 bool IsOverflow) const;
123 std::pair<bool, bool> checkOverflow(CheckerContext &C, SVal RetVal,
124 QualType Res) const;
125
126private:
127 // From: clang/include/clang/Basic/Builtins.def
128 // C++ standard library builtins in namespace 'std'.
129 const CallDescriptionSet BuiltinLikeStdFunctions{
130 {CDM::SimpleFunc, {"std", "addressof"}}, //
131 {CDM::SimpleFunc, {"std", "__addressof"}}, //
132 {CDM::SimpleFunc, {"std", "as_const"}}, //
133 {CDM::SimpleFunc, {"std", "forward"}}, //
134 {CDM::SimpleFunc, {"std", "forward_like"}}, //
135 {CDM::SimpleFunc, {"std", "move"}}, //
136 {CDM::SimpleFunc, {"std", "move_if_noexcept"}}, //
137 };
138
139 bool isBuiltinLikeFunction(const CallEvent &Call) const;
140};
141
142} // namespace
143
144const NoteTag *BuiltinFunctionChecker::createBuiltinOverflowNoteTag(
145 CheckerContext &C, bool overflow, SVal Arg1, SVal Arg2, SVal Result) const {
146 return C.getNoteTag([Result, Arg1, Arg2, overflow](PathSensitiveBugReport &BR,
147 llvm::raw_ostream &OS) {
148 if (!BR.isInteresting(Result))
149 return;
150
151 // Propagate interestingness to input arguments if result is interesting.
152 BR.markInteresting(Arg1);
153 BR.markInteresting(Arg2);
154
155 if (overflow)
156 OS << "Assuming overflow";
157 else
158 OS << "Assuming no overflow";
159 });
160}
161
162std::pair<bool, bool>
163BuiltinFunctionChecker::checkOverflow(CheckerContext &C, SVal RetVal,
164 QualType Res) const {
165 // Calling a builtin with a non-integer type result produces compiler error.
166 assert(Res->isIntegerType());
167
168 unsigned BitWidth = C.getASTContext().getIntWidth(Res);
169 bool IsUnsigned = Res->isUnsignedIntegerType();
170
171 SValBuilder &SVB = C.getSValBuilder();
172 BasicValueFactory &VF = SVB.getBasicValueFactory();
173
174 auto MinValType = llvm::APSInt::getMinValue(BitWidth, IsUnsigned);
175 auto MaxValType = llvm::APSInt::getMaxValue(BitWidth, IsUnsigned);
176 nonloc::ConcreteInt MinVal{VF.getValue(MinValType)};
177 nonloc::ConcreteInt MaxVal{VF.getValue(MaxValType)};
178
179 ProgramStateRef State = C.getState();
180 SVal IsLeMax = SVB.evalBinOp(State, BO_LE, RetVal, MaxVal, Res);
181 SVal IsGeMin = SVB.evalBinOp(State, BO_GE, RetVal, MinVal, Res);
182
183 auto [MayNotOverflow, MayOverflow] =
184 State->assume(IsLeMax.castAs<DefinedOrUnknownSVal>());
185 auto [MayNotUnderflow, MayUnderflow] =
186 State->assume(IsGeMin.castAs<DefinedOrUnknownSVal>());
187
188 return {MayOverflow || MayUnderflow, MayNotOverflow && MayNotUnderflow};
189}
190
191ProgramStateRef BuiltinFunctionChecker::initStateAftetBuiltinOverflow(
192 CheckerContext &C, ProgramStateRef State, const CallEvent &Call,
193 SVal RetVal, bool IsOverflow) const {
194 SValBuilder &SVB = C.getSValBuilder();
195 SVal Arg1 = Call.getArgSVal(0);
196 SVal Arg2 = Call.getArgSVal(1);
197 auto BoolTy = C.getASTContext().BoolTy;
198
199 ProgramStateRef NewState =
200 State->BindExpr(Call.getOriginExpr(), C.getStackFrame(),
201 SVB.makeTruthVal(IsOverflow, BoolTy));
202
203 if (auto L = Call.getArgSVal(2).getAs<Loc>()) {
204 NewState = NewState->bindLoc(*L, RetVal, C.getStackFrame());
205
206 // Propagate taint if any of the arguments were tainted
207 if (isTainted(State, Arg1) || isTainted(State, Arg2))
208 NewState = addTaint(NewState, *L);
209 }
210
211 return NewState;
212}
213
214void BuiltinFunctionChecker::handleOverflowBuiltin(const CallEvent &Call,
215 CheckerContext &C,
217 QualType ResultType) const {
218 // Calling a builtin with an incorrect argument count produces compiler error.
219 assert(Call.getNumArgs() == 3);
220
221 ProgramStateRef State = C.getState();
222 SValBuilder &SVB = C.getSValBuilder();
223
224 SVal Arg1 = Call.getArgSVal(0);
225 SVal Arg2 = Call.getArgSVal(1);
226 QualType Arg1Ty = Call.getArgExpr(0)->getType();
227 QualType Arg2Ty = Call.getArgExpr(1)->getType();
228
229 QualType SufficientlyWideTy =
230 getSufficientTypeForOverflowOp(C, Op, Arg1Ty, Arg2Ty);
231 assert(!SufficientlyWideTy.isNull());
232
233 SVal RetValMax = SVB.evalBinOp(State, Op, Arg1, Arg2, SufficientlyWideTy);
234 SVal RetVal = SVB.evalBinOp(State, Op, Arg1, Arg2, ResultType);
235
236 auto [Overflow, NotOverflow] = checkOverflow(C, RetValMax, ResultType);
237
238 if (NotOverflow) {
239 auto NewState =
240 initStateAftetBuiltinOverflow(C, State, Call, RetVal, false);
241
242 C.addTransition(NewState, createBuiltinOverflowNoteTag(
243 C, /*overflow=*/false, Arg1, Arg2, RetVal));
244 }
245
246 if (Overflow) {
247 auto NewState = initStateAftetBuiltinOverflow(C, State, Call, RetVal, true);
248
249 C.addTransition(NewState, createBuiltinOverflowNoteTag(C, /*overflow=*/true,
250 Arg1, Arg2, RetVal));
251 }
252}
253
254bool BuiltinFunctionChecker::isBuiltinLikeFunction(
255 const CallEvent &Call) const {
256 const auto *FD = llvm::dyn_cast_or_null<FunctionDecl>(Call.getDecl());
257 if (!FD || FD->getNumParams() != 1)
258 return false;
259
260 if (QualType RetTy = FD->getReturnType();
261 !RetTy->isPointerType() && !RetTy->isReferenceType())
262 return false;
263
264 if (QualType ParmTy = FD->getParamDecl(0)->getType();
265 !ParmTy->isPointerType() && !ParmTy->isReferenceType())
266 return false;
267
268 return BuiltinLikeStdFunctions.contains(Call);
269}
270
271bool BuiltinFunctionChecker::evalCall(const CallEvent &Call,
272 CheckerContext &C) const {
273 ProgramStateRef state = C.getState();
274 const auto *FD = dyn_cast_or_null<FunctionDecl>(Call.getDecl());
275 if (!FD)
276 return false;
277
278 const StackFrame *SF = C.getStackFrame();
279 const Expr *CE = Call.getOriginExpr();
280
281 if (isBuiltinLikeFunction(Call)) {
282 C.addTransition(state->BindExpr(CE, SF, Call.getArgSVal(0)));
283 return true;
284 }
285
286 unsigned BI = FD->getBuiltinID();
287
288 switch (BI) {
289 default:
290 return false;
291 case Builtin::BI__builtin_mul_overflow:
292 case Builtin::BI__builtin_smul_overflow:
293 case Builtin::BI__builtin_smull_overflow:
294 case Builtin::BI__builtin_smulll_overflow:
295 case Builtin::BI__builtin_umul_overflow:
296 case Builtin::BI__builtin_umull_overflow:
297 case Builtin::BI__builtin_umulll_overflow:
298 handleOverflowBuiltin(Call, C, BO_Mul,
299 getOverflowBuiltinResultType(Call, C, BI));
300 return true;
301 case Builtin::BI__builtin_sub_overflow:
302 case Builtin::BI__builtin_ssub_overflow:
303 case Builtin::BI__builtin_ssubl_overflow:
304 case Builtin::BI__builtin_ssubll_overflow:
305 case Builtin::BI__builtin_usub_overflow:
306 case Builtin::BI__builtin_usubl_overflow:
307 case Builtin::BI__builtin_usubll_overflow:
308 handleOverflowBuiltin(Call, C, BO_Sub,
309 getOverflowBuiltinResultType(Call, C, BI));
310 return true;
311 case Builtin::BI__builtin_add_overflow:
312 case Builtin::BI__builtin_sadd_overflow:
313 case Builtin::BI__builtin_saddl_overflow:
314 case Builtin::BI__builtin_saddll_overflow:
315 case Builtin::BI__builtin_uadd_overflow:
316 case Builtin::BI__builtin_uaddl_overflow:
317 case Builtin::BI__builtin_uaddll_overflow:
318 handleOverflowBuiltin(Call, C, BO_Add,
319 getOverflowBuiltinResultType(Call, C, BI));
320 return true;
321 case Builtin::BI__builtin_unpredictable:
322 case Builtin::BI__builtin_expect:
323 case Builtin::BI__builtin_expect_with_probability:
324 case Builtin::BI__builtin_assume_aligned:
325 case Builtin::BI__builtin_addressof:
326 case Builtin::BI__builtin_function_start: {
327 // For __builtin_unpredictable, __builtin_expect,
328 // __builtin_expect_with_probability and __builtin_assume_aligned,
329 // just return the value of the subexpression.
330 // __builtin_addressof is going from a reference to a pointer, but those
331 // are represented the same way in the analyzer.
332 assert (Call.getNumArgs() > 0);
333 SVal Arg = Call.getArgSVal(0);
334 C.addTransition(state->BindExpr(CE, SF, Arg));
335 return true;
336 }
337
338 case Builtin::BI__builtin_dynamic_object_size:
339 case Builtin::BI__builtin_object_size:
340 case Builtin::BI__builtin_constant_p: {
341 // This must be resolvable at compile time, so we defer to the constant
342 // evaluator for a value.
343 SValBuilder &SVB = C.getSValBuilder();
344 SVal V = UnknownVal();
345 Expr::EvalResult EVResult;
346 if (CE->EvaluateAsInt(EVResult, C.getASTContext(), Expr::SE_NoSideEffects)) {
347 // Make sure the result has the correct type.
348 llvm::APSInt Result = EVResult.Val.getInt();
349 BasicValueFactory &BVF = SVB.getBasicValueFactory();
350 BVF.getAPSIntType(CE->getType()).apply(Result);
351 V = SVB.makeIntVal(Result);
352 }
353
354 if (FD->getBuiltinID() == Builtin::BI__builtin_constant_p) {
355 // If we didn't manage to figure out if the value is constant or not,
356 // it is safe to assume that it's not constant and unsafe to assume
357 // that it's constant.
358 if (V.isUnknown())
359 V = SVB.makeIntVal(0, CE->getType());
360 }
361
362 C.addTransition(state->BindExpr(CE, SF, V));
363 return true;
364 }
365 }
366}
367
368void ento::registerBuiltinFunctionChecker(CheckerManager &mgr) {
369 mgr.registerChecker<BuiltinFunctionChecker>();
370}
371
372bool ento::shouldRegisterBuiltinFunctionChecker(const CheckerManager &mgr) {
373 return true;
374}
#define V(N, I)
Defines enum values for all the target-independent builtin functions.
Result
Implement __builtin_bit_cast and related operations.
APSInt & getInt()
Definition APValue.h:511
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition ASTContext.h:223
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:4063
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:692
QualType getType() const
Definition Expr.h:145
A (possibly-)qualified type.
Definition TypeBase.h:938
bool isNull() const
Return true if this QualType doesn't point to a type yet.
Definition TypeBase.h:1005
bool isSignedIntegerType() const
Return true if this is an integer type that is signed, according to C99 6.2.5p4 [char,...
Definition Type.cpp:2296
bool isIntegerType() const
isIntegerType() does not include complex integers (a GCC extension).
Definition TypeBase.h:9155
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:2364
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:152
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:565
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:57
T castAs() const
Convert to the specified SVal type, asserting that this SVal is of the desired type.
Definition SVals.h:84
bool isTainted(ProgramStateRef State, const Expr *E, const StackFrame *SF, TaintTagType Kind=TaintTagGeneric)
Check if the expression has a tainted value in the given state.
Definition Taint.cpp:147
ProgramStateRef addTaint(ProgramStateRef State, const Expr *E, const StackFrame *SF, TaintTagType Kind=TaintTagGeneric)
Create a new state in which the value of the expression is marked as tainted.
Definition Taint.cpp:46
IntrusiveRefCntPtr< const ProgramState > ProgramStateRef
@ OS
Indicates that the tracking object is a descendant of a referenced-counted OSObject,...
Top level wrappers for InstallAPI frontend operations.
@ Result
The result type of a method or function.
Definition TypeBase.h:906
APValue Val
Val - This is the value the expression can be folded to.
Definition Expr.h:668