From bdecb5f0d423364d024597699ffd3838cea08035 Mon Sep 17 00:00:00 2001 From: Artem Dergachev Date: Fri, 12 Jan 2018 22:12:11 +0000 Subject: [PATCH] [analyzer] Don't flag strcpy of string literals into sufficiently large buffers. MIME-Version: 1.0 Content-Type: text/plain; charset=utf8 Content-Transfer-Encoding: 8bit In the security package, we have a simple syntactic check that warns about strcpy() being insecure, due to potential buffer overflows. Suppress that check's warning in the trivial situation when the source is an immediate null-terminated string literal and the target is an immediate sufficiently large buffer. Patch by András Leitereg! Differential Revision: https://reviews.llvm.org/D41384 git-svn-id: https://llvm.org/svn/llvm-project/cfe/trunk@322410 91177308-0d34-0410-b5e6-96231b3b80d8 --- .../Checkers/CheckSecuritySyntaxOnly.cpp | 11 +++++++++++ test/Analysis/security-syntax-checks.m | 10 ++++++++++ 2 files changed, 21 insertions(+) diff --git a/lib/StaticAnalyzer/Checkers/CheckSecuritySyntaxOnly.cpp b/lib/StaticAnalyzer/Checkers/CheckSecuritySyntaxOnly.cpp index 6dbacad7f2..62831be26e 100644 --- a/lib/StaticAnalyzer/Checkers/CheckSecuritySyntaxOnly.cpp +++ b/lib/StaticAnalyzer/Checkers/CheckSecuritySyntaxOnly.cpp @@ -510,6 +510,17 @@ void WalkAST::checkCall_strcpy(const CallExpr *CE, const FunctionDecl *FD) { if (!checkCall_strCommon(CE, FD)) return; + const auto *Target = CE->getArg(0)->IgnoreImpCasts(), + *Source = CE->getArg(1)->IgnoreImpCasts(); + if (const auto *DeclRef = dyn_cast(Target)) + if (const auto *Array = dyn_cast(DeclRef->getType())) { + uint64_t ArraySize = BR.getContext().getTypeSize(Array) / 8; + if (const auto *String = dyn_cast(Source)) { + if (ArraySize >= String->getLength() + 1) + return; + } + } + // Issue a warning. PathDiagnosticLocation CELoc = PathDiagnosticLocation::createBegin(CE, BR.getSourceManager(), AC); diff --git a/test/Analysis/security-syntax-checks.m b/test/Analysis/security-syntax-checks.m index 04a4c7d866..8560ba29e7 100644 --- a/test/Analysis/security-syntax-checks.m +++ b/test/Analysis/security-syntax-checks.m @@ -146,6 +146,16 @@ void test_strcpy() { strcpy(x, y); //expected-warning{{Call to function 'strcpy' is insecure as it does not provide bounding of the memory buffer. Replace unbounded copy functions with analogous functions that support length arguments such as 'strlcpy'. CWE-119}} } +void test_strcpy_2() { + char x[4]; + strcpy(x, "abcd"); //expected-warning{{Call to function 'strcpy' is insecure as it does not provide bounding of the memory buffer. Replace unbounded copy functions with analogous functions that support length arguments such as 'strlcpy'. CWE-119}} +} + +void test_strcpy_safe() { + char x[5]; + strcpy(x, "abcd"); +} + //===----------------------------------------------------------------------=== // strcat() //===----------------------------------------------------------------------=== -- 2.50.1