diff options
| author | Ted Kremenek <kremenek@apple.com> | 2011-02-16 01:57:07 +0000 |
|---|---|---|
| committer | Ted Kremenek <kremenek@apple.com> | 2011-02-16 01:57:07 +0000 |
| commit | 64699befcd5d173d787ae7ac8db0f859f4dd0067 (patch) | |
| tree | 1dd04658531bcce5f5f29cb5386bb8c50f6df025 /clang/lib | |
| parent | af1c83fbe7e8eb6c5450231ba26ef08f7e5a29ef (diff) | |
| download | bcm5719-llvm-64699befcd5d173d787ae7ac8db0f859f4dd0067.tar.gz bcm5719-llvm-64699befcd5d173d787ae7ac8db0f859f4dd0067.zip | |
Add trivial buffer overflow checking in Sema.
llvm-svn: 125640
Diffstat (limited to 'clang/lib')
| -rw-r--r-- | clang/lib/Sema/SemaChecking.cpp | 30 | ||||
| -rw-r--r-- | clang/lib/Sema/SemaExpr.cpp | 8 |
2 files changed, 38 insertions, 0 deletions
diff --git a/clang/lib/Sema/SemaChecking.cpp b/clang/lib/Sema/SemaChecking.cpp index 03ce7f3708a..ea1f07d7834 100644 --- a/clang/lib/Sema/SemaChecking.cpp +++ b/clang/lib/Sema/SemaChecking.cpp @@ -3080,3 +3080,33 @@ void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) { << TRange << Op->getSourceRange(); } +void Sema::CheckArrayAccess(const clang::ArraySubscriptExpr *ae) { + const DeclRefExpr *dr = + dyn_cast<DeclRefExpr>(ae->getBase()->IgnoreParenImpCasts()); + if (!dr) + return; + const VarDecl *vd = cast<VarDecl>(dr->getDecl()); + const ConstantArrayType *cat = Context.getAsConstantArrayType(vd->getType()); + if (!cat) + return; + const Expr *idx = ae->getIdx(); + if (idx->isValueDependent()) + return; + llvm::APSInt result; + if (!idx->isIntegerConstantExpr(result, Context)) + return; + unsigned kind = 2; + if (result.slt(0)) + kind = /* precedes */ 0; + else { + const llvm::APInt &size = cat->getSize(); + if (size.getBitWidth() > result.getBitWidth()) + result = result.sext(size.getBitWidth()); + if (result.sge(size)) + kind = /* excedes */ 1; + } + if (kind < 2) + Diag(ae->getBase()->getLocEnd(), diag::warn_array_index_out_of_bounds) + << kind << idx->getSourceRange(); +} + diff --git a/clang/lib/Sema/SemaExpr.cpp b/clang/lib/Sema/SemaExpr.cpp index b0c337149d9..760d5d58bc4 100644 --- a/clang/lib/Sema/SemaExpr.cpp +++ b/clang/lib/Sema/SemaExpr.cpp @@ -294,6 +294,9 @@ void Sema::DefaultLvalueConversion(Expr *&E) { if (T.hasQualifiers()) T = T.getUnqualifiedType(); + if (const ArraySubscriptExpr *ae = dyn_cast<ArraySubscriptExpr>(E)) + CheckArrayAccess(ae); + E = ImplicitCastExpr::Create(Context, T, CK_LValueToRValue, E, 0, VK_RValue); } @@ -7242,6 +7245,11 @@ QualType Sema::CheckAssignmentOperands(Expr *LHS, Expr *&RHS, Diag(UO->getOperatorLoc(), diag::note_indirection_through_null); } + // Check for trivial buffer overflows. + if (const ArraySubscriptExpr *ae + = dyn_cast<ArraySubscriptExpr>(LHS->IgnoreParenCasts())) + CheckArrayAccess(ae); + // C99 6.5.16p3: The type of an assignment expression is the type of the // left operand unless the left operand has qualified type, in which case // it is the unqualified version of the type of the left operand. |

