diff options
author | Nico Weber <nicolasweber@gmx.de> | 2011-06-14 16:14:58 +0000 |
---|---|---|
committer | Nico Weber <nicolasweber@gmx.de> | 2011-06-14 16:14:58 +0000 |
commit | e4a1c64700304459ac436fe29cb498f2da3b6194 (patch) | |
tree | 8fa5792cf09d28c8103bb80f2e03fc2fa3da058b /lib/Sema/SemaChecking.cpp | |
parent | 63f04ab297157c5905975e8f2c807b35251dace7 (diff) |
Warn on memset(ptr, 0, sizeof(ptr)). Diagnostic wording by Jordy Rose.
git-svn-id: https://llvm.org/svn/llvm-project/cfe/trunk@132996 91177308-0d34-0410-b5e6-96231b3b80d8
Diffstat (limited to 'lib/Sema/SemaChecking.cpp')
-rw-r--r-- | lib/Sema/SemaChecking.cpp | 28 |
1 files changed, 27 insertions, 1 deletions
diff --git a/lib/Sema/SemaChecking.cpp b/lib/Sema/SemaChecking.cpp index 9c47e1e1e2..389dd91f32 100644 --- a/lib/Sema/SemaChecking.cpp +++ b/lib/Sema/SemaChecking.cpp @@ -1812,6 +1812,20 @@ static bool isDynamicClassType(QualType T) { return false; } +/// \brief If E is a sizeof expression, returns the expression's type in +/// OutType. +static bool sizeofExprType(const Expr* E, QualType *OutType) { + if (const UnaryExprOrTypeTraitExpr *SizeOf = + dyn_cast<UnaryExprOrTypeTraitExpr>(E)) { + if (SizeOf->getKind() != clang::UETT_SizeOf) + return false; + + *OutType = SizeOf->getTypeOfArgument(); + return true; + } + return false; +} + /// \brief Check for dangerous or invalid arguments to memset(). /// /// This issues warnings on known problematic, dangerous or unspecified @@ -1827,8 +1841,10 @@ void Sema::CheckMemsetcpymoveArguments(const CallExpr *Call, return; unsigned LastArg = FnName->isStr("memset")? 1 : 2; + const Expr *LenExpr = Call->getArg(2)->IgnoreParenImpCasts(); for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) { const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts(); + SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange(); QualType DestTy = Dest->getType(); if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) { @@ -1836,6 +1852,17 @@ void Sema::CheckMemsetcpymoveArguments(const CallExpr *Call, if (PointeeTy->isVoidType()) continue; + // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). + QualType SizeofTy; + if (sizeofExprType(LenExpr, &SizeofTy) && + Context.typesAreCompatible(SizeofTy, DestTy)) { + // Note: This complains about sizeof(typeof(p)) as well. + SourceLocation loc = LenExpr->getSourceRange().getBegin(); + Diag(loc, diag::warn_sizeof_pointer) + << SizeofTy << PointeeTy << ArgIdx << FnName; + break; + } + // Always complain about dynamic classes. if (isDynamicClassType(PointeeTy)) { DiagRuntimeBehavior( @@ -1847,7 +1874,6 @@ void Sema::CheckMemsetcpymoveArguments(const CallExpr *Call, continue; } - SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange(); DiagRuntimeBehavior( Dest->getExprLoc(), Dest, PDiag(diag::note_bad_memaccess_silence) |