25#include "llvm/ADT/APSInt.h"
26#include "llvm/ADT/SmallVector.h"
35struct MallocOverflowCheck {
43 : call(call), mulop(m), variable(
v), maxVal(
std::move(val)) {}
46class MallocOverflowSecurityChecker :
public Checker<check::ASTCodeBody> {
51 void CheckMallocArgument(
55 void OutputPossibleOverflows(
64 return (op == BO_Mul) && (Val == 0);
67void MallocOverflowSecurityChecker::CheckMallocArgument(
86 if (mulop ==
nullptr && opc == BO_Mul)
88 if (opc != BO_Mul && opc != BO_Add && opc != BO_Sub && opc != BO_Shl)
91 const Expr *lhs = binop->getLHS();
92 const Expr *rhs = binop->getRHS();
98 }
else if ((opc == BO_Add || opc == BO_Mul) &&
106 }
else if (isa<DeclRefExpr, MemberExpr>(e))
112 if (mulop ==
nullptr)
119 PossibleMallocOverflows.push_back(
120 MallocOverflowCheck(TheCall, mulop, e, maxVal));
125class CheckOverflowOps :
131 theVecType &toScanFor;
134 bool isIntZeroExpr(
const Expr *E)
const {
139 return Result.Val.getInt() == 0;
148 template <
typename T1>
149 void Erase(
const T1 *DR,
150 llvm::function_ref<
bool(
const MallocOverflowCheck &)> Pred) {
151 auto P = [DR, Pred](
const MallocOverflowCheck &Check) {
152 if (
const auto *CheckDR = dyn_cast<T1>(Check.variable))
153 return getDecl(CheckDR) == getDecl(DR) && Pred(Check);
156 llvm::erase_if(toScanFor,
P);
159 void CheckExpr(
const Expr *E_p) {
161 const auto PrecedesMalloc = [E,
this](
const MallocOverflowCheck &
c) {
165 if (
const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E))
166 Erase<DeclRefExpr>(DR, PrecedesMalloc);
167 else if (
const auto *ME = dyn_cast<MemberExpr>(E)) {
168 Erase<MemberExpr>(ME, PrecedesMalloc);
178 bool assignKnown =
false;
179 bool numeratorKnown =
false, denomKnown =
false;
193 if (BOp->getOpcode() == BO_Div) {
197 denomVal = Result.Val.getInt();
202 numeratorKnown =
true;
205 if (!assignKnown && !denomKnown)
207 auto denomExtVal = denomVal.getExtValue();
216 auto pred = [assignKnown, numeratorKnown,
217 denomExtVal](
const MallocOverflowCheck &Check) {
218 return assignKnown ||
219 (numeratorKnown && (denomExtVal >= Check.maxVal.getExtValue()));
222 if (
const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E))
223 Erase<DeclRefExpr>(DR, pred);
224 else if (
const auto *ME = dyn_cast<MemberExpr>(E))
225 Erase<MemberExpr>(ME, pred);
235 if (!isIntZeroExpr(lhs) && !isIntZeroExpr(rhs)) {
241 CheckAssignmentExpr(E);
250 void VisitForStmt(
ForStmt *S) {
253 void VisitDoStmt(
DoStmt *S) {
259 toScanFor(
v), Context(ctx)
271void MallocOverflowSecurityChecker::OutputPossibleOverflows(
275 if (PossibleMallocOverflows.empty())
279 CheckOverflowOps
c(PossibleMallocOverflows, BR.
getContext());
283 for (
const MallocOverflowCheck &Check : PossibleMallocOverflows) {
286 "the computation of the size of the memory allocation may overflow",
289 Check.mulop->getSourceRange());
293void MallocOverflowSecurityChecker::checkASTCodeBody(
const Decl *D,
308 if (std::optional<CFGStmt> CS = bi->getAs<
CFGStmt>()) {
309 if (
const CallExpr *TheCall = dyn_cast<CallExpr>(CS->getStmt())) {
322 if (FnInfo->
isStr(
"malloc") || FnInfo->
isStr(
"_MALLOC")) {
324 CheckMallocArgument(PossibleMallocOverflows, TheCall,
332 OutputPossibleOverflows(PossibleMallocOverflows, D, BR, mgr);
335void ento::registerMallocOverflowSecurityChecker(
CheckerManager &mgr) {
339bool ento::shouldRegisterMallocOverflowSecurityChecker(
const CheckerManager &mgr) {
static bool EvaluatesToZero(APSInt &Val, BinaryOperatorKind op)
__device__ __2f16 float c
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
SourceManager & getSourceManager()
A builtin binary operation expression such as "x + y" or "x <= y".
static bool isComparisonOp(Opcode Opc)
static bool isAssignmentOp(Opcode Opc)
Represents a single basic block in a source-level CFG.
ElementList::iterator iterator
Represents a source-level, intra-procedural CFG that represents the control-flow of a Stmt.
CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
Expr * getArg(unsigned Arg)
getArg - Return the specified argument.
FunctionDecl * getDirectCallee()
If the callee is a FunctionDecl, return it. Otherwise return null.
unsigned getNumArgs() const
getNumArgs - Return the number of actual arguments to this call.
A reference to a declared variable, function, enum, etc.
Decl - This represents one declaration (or definition), e.g.
DoStmt - This represents a 'do/while' stmt.
const ASTContext & Context
EvaluatedExprVisitor - This class visits 'Expr *'s.
This represents one expression.
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,...
llvm::APSInt EvaluateKnownConstInt(const ASTContext &Ctx, SmallVectorImpl< PartialDiagnosticAt > *Diag=nullptr) const
EvaluateKnownConstInt - Call EvaluateAsRValue and return the folded integer.
Expr * IgnoreParenImpCasts() LLVM_READONLY
Skip past any parentheses and implicit casts which might surround this expression until reaching a fi...
bool isEvaluatable(const ASTContext &Ctx, SideEffectsKind AllowSideEffects=SE_NoSideEffects) const
isEvaluatable - Call EvaluateAsRValue to see if this expression can be constant folded without side-e...
SourceLocation getExprLoc() const LLVM_READONLY
getExprLoc - Return the preferred location for the arrow when diagnosing a problem with a generic exp...
ForStmt - This represents a 'for (init;cond;inc)' stmt.
Represents a function declaration or definition.
One of these records is kept for each identifier that is lexed.
bool isStr(const char(&Str)[StrLen]) const
Return true if this is the identifier for the specified string.
MemberExpr - [C99 6.5.2.3] Structure and Union Members.
ValueDecl * getMemberDecl() const
Retrieve the member declaration to which this expression refers.
IdentifierInfo * getIdentifier() const
Get the identifier that names this declaration, if there is one.
bool isBeforeInTranslationUnit(SourceLocation LHS, SourceLocation RHS) const
Determines the order of 2 source locations in the translation unit.
RetTy Visit(PTR(Stmt) S, ParamTys... P)
bool isIntegralOrEnumerationType() const
Determine whether this type is an integral or enumeration type.
WhileStmt - This represents a 'while' stmt.
ASTContext & getASTContext() override
AnalysisDeclContext * getAnalysisDeclContext(const Decl *D)
CFG * getCFG(Decl const *D)
BugReporter is a utility class for generating PathDiagnostics for analysis.
const SourceManager & getSourceManager()
void EmitBasicReport(const Decl *DeclWithIssue, const CheckerBase *Checker, StringRef BugName, StringRef BugCategory, StringRef BugStr, PathDiagnosticLocation Loc, ArrayRef< SourceRange > Ranges=std::nullopt, ArrayRef< FixItHint > Fixits=std::nullopt)
ASTContext & getContext()
CHECKER * registerChecker(AT &&... Args)
Used to register checkers.
static PathDiagnosticLocation createOperatorLoc(const BinaryOperator *BO, const SourceManager &SM)
Create the location for the operator of the binary expression.
const char *const UnixAPI
@ Result
The result type of a method or function.
EvalResult is a struct with detailed info about an evaluated expression.