[clang] af99236 - Don't diagnose unused but set when the Cleanup attribute is used.

2021-09-22 Thread Michael Benfield via cfe-commits

Author: Michael Benfield
Date: 2021-09-22T17:48:09Z
New Revision: af99236747872af7e77092cbf6ddd18fa8623a2f

URL: 
https://github.com/llvm/llvm-project/commit/af99236747872af7e77092cbf6ddd18fa8623a2f
DIFF: 
https://github.com/llvm/llvm-project/commit/af99236747872af7e77092cbf6ddd18fa8623a2f.diff

LOG: Don't diagnose unused but set when the Cleanup attribute is used.

This applies to -Wunused-but-set-variable and
-Wunused-but-set-parameter.

This addresses bug 51865.

Differential Revision: https://reviews.llvm.org/D109862

Added: 


Modified: 
clang/lib/Sema/SemaDecl.cpp
clang/test/Sema/warn-unused-but-set-variables.c

Removed: 




diff  --git a/clang/lib/Sema/SemaDecl.cpp b/clang/lib/Sema/SemaDecl.cpp
index cc3417d4ccba..13389ebdd72f 100644
--- a/clang/lib/Sema/SemaDecl.cpp
+++ b/clang/lib/Sema/SemaDecl.cpp
@@ -1921,8 +1921,10 @@ void Sema::DiagnoseUnusedDecl(const NamedDecl *D) {
 }
 
 void Sema::DiagnoseUnusedButSetDecl(const VarDecl *VD) {
-  // If it's not referenced, it can't be set.
-  if (!VD->isReferenced() || !VD->getDeclName() || VD->hasAttr())
+  // If it's not referenced, it can't be set. If it has the Cleanup attribute,
+  // it's not really unused.
+  if (!VD->isReferenced() || !VD->getDeclName() || VD->hasAttr() ||
+  VD->hasAttr())
 return;
 
   const auto *Ty = VD->getType().getTypePtr()->getBaseElementTypeUnsafe();

diff  --git a/clang/test/Sema/warn-unused-but-set-variables.c 
b/clang/test/Sema/warn-unused-but-set-variables.c
index a8d05243321f..38042ba014c4 100644
--- a/clang/test/Sema/warn-unused-but-set-variables.c
+++ b/clang/test/Sema/warn-unused-but-set-variables.c
@@ -49,3 +49,13 @@ void f2 (void) {
   x = 0;
   (void) sizeof(x);
 }
+
+void for_cleanup(int *x) {
+  *x = 0;
+}
+
+void f3(void) {
+  // Don't warn if the __cleanup__ attribute is used.
+  __attribute__((__cleanup__(for_cleanup))) int x;
+  x = 5;
+}



___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] 15e3d39 - [clang] Fortify warning for scanf calls with field width too big.

2021-10-27 Thread Michael Benfield via cfe-commits

Author: Michael Benfield
Date: 2021-10-28T02:52:03Z
New Revision: 15e3d39110fa4449be4f56196af3bc81b623f3ab

URL: 
https://github.com/llvm/llvm-project/commit/15e3d39110fa4449be4f56196af3bc81b623f3ab
DIFF: 
https://github.com/llvm/llvm-project/commit/15e3d39110fa4449be4f56196af3bc81b623f3ab.diff

LOG: [clang] Fortify warning for scanf calls with field width too big.

Differential Revision: https://reviews.llvm.org/D111833

Added: 
clang/test/Sema/warn-fortify-scanf.c

Modified: 
clang/include/clang/Basic/DiagnosticSemaKinds.td
clang/lib/Sema/SemaChecking.cpp

Removed: 




diff  --git a/clang/include/clang/Basic/DiagnosticSemaKinds.td 
b/clang/include/clang/Basic/DiagnosticSemaKinds.td
index 09482d238ff3..920146f71bd8 100644
--- a/clang/include/clang/Basic/DiagnosticSemaKinds.td
+++ b/clang/include/clang/Basic/DiagnosticSemaKinds.td
@@ -833,6 +833,10 @@ def warn_fortify_source_format_overflow : Warning<
   " but format string expands to at least %2">,
   InGroup;
 
+def warn_fortify_scanf_overflow : Warning<
+  "'%0' may overflow; destination buffer in argument %1 has size "
+  "%2, but the corresponding field width plus NUL byte is %3">,
+  InGroup;
 
 /// main()
 // static main() is not an error in C, just in C++.

diff  --git a/clang/lib/Sema/SemaChecking.cpp b/clang/lib/Sema/SemaChecking.cpp
index 147f50aeed97..e11966020ae9 100644
--- a/clang/lib/Sema/SemaChecking.cpp
+++ b/clang/lib/Sema/SemaChecking.cpp
@@ -408,6 +408,50 @@ static bool SemaBuiltinCallWithStaticChain(Sema &S, 
CallExpr *BuiltinCall) {
 
 namespace {
 
+class ScanfDiagnosticFormatHandler
+: public analyze_format_string::FormatStringHandler {
+  // Accepts the argument index (relative to the first destination index) of 
the
+  // argument whose size we want.
+  using ComputeSizeFunction =
+  llvm::function_ref(unsigned)>;
+
+  // Accepts the argument index (relative to the first destination index), the
+  // destination size, and the source size).
+  using DiagnoseFunction =
+  llvm::function_ref;
+
+  ComputeSizeFunction ComputeSizeArgument;
+  DiagnoseFunction Diagnose;
+
+public:
+  ScanfDiagnosticFormatHandler(ComputeSizeFunction ComputeSizeArgument,
+   DiagnoseFunction Diagnose)
+  : ComputeSizeArgument(ComputeSizeArgument), Diagnose(Diagnose) {}
+
+  bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
+const char *StartSpecifier,
+unsigned specifierLen) override {
+auto OptionalFW = FS.getFieldWidth();
+if (OptionalFW.getHowSpecified() !=
+analyze_format_string::OptionalAmount::HowSpecified::Constant)
+  return true;
+
+// We have to write the data plus a NUL byte.
+unsigned SourceSize = OptionalFW.getConstantAmount() + 1;
+
+auto DestSizeAPS = ComputeSizeArgument(FS.getArgIndex());
+if (!DestSizeAPS)
+  return true;
+
+unsigned DestSize = DestSizeAPS->getZExtValue();
+
+if (DestSize < SourceSize)
+  Diagnose(FS.getArgIndex(), DestSize, SourceSize);
+
+return true;
+  }
+};
+
 class EstimateSizeFormatHandler
 : public analyze_format_string::FormatStringHandler {
   size_t Size;
@@ -615,9 +659,12 @@ void 
Sema::checkFortifiedBuiltinMemoryFunction(FunctionDecl *FD,
 // (potentially) more strict checking mode. Otherwise, conservatively 
assume
 // type 0.
 int BOSType = 0;
-if (const auto *POS =
-FD->getParamDecl(Index)->getAttr())
-  BOSType = POS->getType();
+// This check can fail for variadic functions.
+if (Index < FD->getNumParams()) {
+  if (const auto *POS =
+  FD->getParamDecl(Index)->getAttr())
+BOSType = POS->getType();
+}
 
 const Expr *ObjArg = TheCall->getArg(Index);
 uint64_t Result;
@@ -642,6 +689,20 @@ void 
Sema::checkFortifiedBuiltinMemoryFunction(FunctionDecl *FD,
   unsigned DiagID = 0;
   bool IsChkVariant = false;
 
+  auto GetFunctionName = [&]() {
+StringRef FunctionName = getASTContext().BuiltinInfo.getName(BuiltinID);
+// Skim off the details of whichever builtin was called to produce a better
+// diagnostic, as it's unlikely that the user wrote the __builtin
+// explicitly.
+if (IsChkVariant) {
+  FunctionName = FunctionName.drop_front(std::strlen("__builtin___"));
+  FunctionName = FunctionName.drop_back(std::strlen("_chk"));
+} else if (FunctionName.startswith("__builtin_")) {
+  FunctionName = FunctionName.drop_front(std::strlen("__builtin_"));
+}
+return FunctionName;
+  };
+
   switch (BuiltinID) {
   default:
 return;
@@ -661,6 +722,61 @@ void 
Sema::checkFortifiedBuiltinMemoryFunction(FunctionDecl *FD,
 break;
   }
 
+  case Builtin::BIscanf:
+  case Builtin::BIfscanf:
+  case Builtin::BIsscanf: {
+unsigned FormatIndex = 1;
+unsigned DataIndex = 2;
+if (BuiltinID == Builtin::BIscanf) {
+  Fo

[clang] 5a8c173 - [clang] Fortify warning for scanf calls with field width too big.

2021-11-01 Thread Michael Benfield via cfe-commits

Author: Michael Benfield
Date: 2021-11-01T17:17:37Z
New Revision: 5a8c1736289f2b1df10df38e7a9e4d208a7586a6

URL: 
https://github.com/llvm/llvm-project/commit/5a8c1736289f2b1df10df38e7a9e4d208a7586a6
DIFF: 
https://github.com/llvm/llvm-project/commit/5a8c1736289f2b1df10df38e7a9e4d208a7586a6.diff

LOG: [clang] Fortify warning for scanf calls with field width too big.

Differential Revision: https://reviews.llvm.org/D111833

Added: 
clang/test/Sema/warn-fortify-scanf.c

Modified: 
clang/include/clang/Basic/DiagnosticSemaKinds.td
clang/lib/Sema/SemaChecking.cpp

Removed: 




diff  --git a/clang/include/clang/Basic/DiagnosticSemaKinds.td 
b/clang/include/clang/Basic/DiagnosticSemaKinds.td
index d37c8e9266e9b..8a098d37ec4c3 100644
--- a/clang/include/clang/Basic/DiagnosticSemaKinds.td
+++ b/clang/include/clang/Basic/DiagnosticSemaKinds.td
@@ -833,6 +833,10 @@ def warn_fortify_source_format_overflow : Warning<
   " but format string expands to at least %2">,
   InGroup;
 
+def warn_fortify_scanf_overflow : Warning<
+  "'%0' may overflow; destination buffer in argument %1 has size "
+  "%2, but the corresponding specifier may require size %3">,
+  InGroup;
 
 /// main()
 // static main() is not an error in C, just in C++.

diff  --git a/clang/lib/Sema/SemaChecking.cpp b/clang/lib/Sema/SemaChecking.cpp
index bf458f914c111..8bf696a721027 100644
--- a/clang/lib/Sema/SemaChecking.cpp
+++ b/clang/lib/Sema/SemaChecking.cpp
@@ -408,6 +408,61 @@ static bool SemaBuiltinCallWithStaticChain(Sema &S, 
CallExpr *BuiltinCall) {
 
 namespace {
 
+class ScanfDiagnosticFormatHandler
+: public analyze_format_string::FormatStringHandler {
+  // Accepts the argument index (relative to the first destination index) of 
the
+  // argument whose size we want.
+  using ComputeSizeFunction =
+  llvm::function_ref(unsigned)>;
+
+  // Accepts the argument index (relative to the first destination index), the
+  // destination size, and the source size).
+  using DiagnoseFunction =
+  llvm::function_ref;
+
+  ComputeSizeFunction ComputeSizeArgument;
+  DiagnoseFunction Diagnose;
+
+public:
+  ScanfDiagnosticFormatHandler(ComputeSizeFunction ComputeSizeArgument,
+   DiagnoseFunction Diagnose)
+  : ComputeSizeArgument(ComputeSizeArgument), Diagnose(Diagnose) {}
+
+  bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
+const char *StartSpecifier,
+unsigned specifierLen) override {
+unsigned NulByte = 0;
+switch ((FS.getConversionSpecifier().getKind())) {
+default:
+  return true;
+case analyze_format_string::ConversionSpecifier::sArg:
+case analyze_format_string::ConversionSpecifier::ScanListArg:
+  NulByte = 1;
+  break;
+case analyze_format_string::ConversionSpecifier::cArg:
+  break;
+}
+
+auto OptionalFW = FS.getFieldWidth();
+if (OptionalFW.getHowSpecified() !=
+analyze_format_string::OptionalAmount::HowSpecified::Constant)
+  return true;
+
+unsigned SourceSize = OptionalFW.getConstantAmount() + NulByte;
+
+auto DestSizeAPS = ComputeSizeArgument(FS.getArgIndex());
+if (!DestSizeAPS)
+  return true;
+
+unsigned DestSize = DestSizeAPS->getZExtValue();
+
+if (DestSize < SourceSize)
+  Diagnose(FS.getArgIndex(), DestSize, SourceSize);
+
+return true;
+  }
+};
+
 class EstimateSizeFormatHandler
 : public analyze_format_string::FormatStringHandler {
   size_t Size;
@@ -615,9 +670,12 @@ void 
Sema::checkFortifiedBuiltinMemoryFunction(FunctionDecl *FD,
 // (potentially) more strict checking mode. Otherwise, conservatively 
assume
 // type 0.
 int BOSType = 0;
-if (const auto *POS =
-FD->getParamDecl(Index)->getAttr())
-  BOSType = POS->getType();
+// This check can fail for variadic functions.
+if (Index < FD->getNumParams()) {
+  if (const auto *POS =
+  FD->getParamDecl(Index)->getAttr())
+BOSType = POS->getType();
+}
 
 const Expr *ObjArg = TheCall->getArg(Index);
 uint64_t Result;
@@ -642,6 +700,20 @@ void 
Sema::checkFortifiedBuiltinMemoryFunction(FunctionDecl *FD,
   unsigned DiagID = 0;
   bool IsChkVariant = false;
 
+  auto GetFunctionName = [&]() {
+StringRef FunctionName = getASTContext().BuiltinInfo.getName(BuiltinID);
+// Skim off the details of whichever builtin was called to produce a better
+// diagnostic, as it's unlikely that the user wrote the __builtin
+// explicitly.
+if (IsChkVariant) {
+  FunctionName = FunctionName.drop_front(std::strlen("__builtin___"));
+  FunctionName = FunctionName.drop_back(std::strlen("_chk"));
+} else if (FunctionName.startswith("__builtin_")) {
+  FunctionName = FunctionName.drop_front(std::strlen("__builtin_"));
+}
+return FunctionName;
+  };
+
   switch (BuiltinID) {
   def

[clang] d51a829 - Revert "[clang] Fortify warning for scanf calls with field width too big."

2021-11-01 Thread Michael Benfield via cfe-commits

Author: Michael Benfield
Date: 2021-11-01T19:36:45Z
New Revision: d51a8296d374122c937df708f5fa1500218baa5c

URL: 
https://github.com/llvm/llvm-project/commit/d51a8296d374122c937df708f5fa1500218baa5c
DIFF: 
https://github.com/llvm/llvm-project/commit/d51a8296d374122c937df708f5fa1500218baa5c.diff

LOG: Revert "[clang] Fortify warning for scanf calls with field width too big."

This reverts commit 5a8c1736289f2b1df10df38e7a9e4d208a7586a6.

The warning needs to correctly handle * specifiers (which are to be
ignored).

Added: 


Modified: 
clang/include/clang/Basic/DiagnosticSemaKinds.td
clang/lib/Sema/SemaChecking.cpp

Removed: 
clang/test/Sema/warn-fortify-scanf.c



diff  --git a/clang/include/clang/Basic/DiagnosticSemaKinds.td 
b/clang/include/clang/Basic/DiagnosticSemaKinds.td
index 8a098d37ec4c3..d37c8e9266e9b 100644
--- a/clang/include/clang/Basic/DiagnosticSemaKinds.td
+++ b/clang/include/clang/Basic/DiagnosticSemaKinds.td
@@ -833,10 +833,6 @@ def warn_fortify_source_format_overflow : Warning<
   " but format string expands to at least %2">,
   InGroup;
 
-def warn_fortify_scanf_overflow : Warning<
-  "'%0' may overflow; destination buffer in argument %1 has size "
-  "%2, but the corresponding specifier may require size %3">,
-  InGroup;
 
 /// main()
 // static main() is not an error in C, just in C++.

diff  --git a/clang/lib/Sema/SemaChecking.cpp b/clang/lib/Sema/SemaChecking.cpp
index 8bf696a721027..bf458f914c111 100644
--- a/clang/lib/Sema/SemaChecking.cpp
+++ b/clang/lib/Sema/SemaChecking.cpp
@@ -408,61 +408,6 @@ static bool SemaBuiltinCallWithStaticChain(Sema &S, 
CallExpr *BuiltinCall) {
 
 namespace {
 
-class ScanfDiagnosticFormatHandler
-: public analyze_format_string::FormatStringHandler {
-  // Accepts the argument index (relative to the first destination index) of 
the
-  // argument whose size we want.
-  using ComputeSizeFunction =
-  llvm::function_ref(unsigned)>;
-
-  // Accepts the argument index (relative to the first destination index), the
-  // destination size, and the source size).
-  using DiagnoseFunction =
-  llvm::function_ref;
-
-  ComputeSizeFunction ComputeSizeArgument;
-  DiagnoseFunction Diagnose;
-
-public:
-  ScanfDiagnosticFormatHandler(ComputeSizeFunction ComputeSizeArgument,
-   DiagnoseFunction Diagnose)
-  : ComputeSizeArgument(ComputeSizeArgument), Diagnose(Diagnose) {}
-
-  bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
-const char *StartSpecifier,
-unsigned specifierLen) override {
-unsigned NulByte = 0;
-switch ((FS.getConversionSpecifier().getKind())) {
-default:
-  return true;
-case analyze_format_string::ConversionSpecifier::sArg:
-case analyze_format_string::ConversionSpecifier::ScanListArg:
-  NulByte = 1;
-  break;
-case analyze_format_string::ConversionSpecifier::cArg:
-  break;
-}
-
-auto OptionalFW = FS.getFieldWidth();
-if (OptionalFW.getHowSpecified() !=
-analyze_format_string::OptionalAmount::HowSpecified::Constant)
-  return true;
-
-unsigned SourceSize = OptionalFW.getConstantAmount() + NulByte;
-
-auto DestSizeAPS = ComputeSizeArgument(FS.getArgIndex());
-if (!DestSizeAPS)
-  return true;
-
-unsigned DestSize = DestSizeAPS->getZExtValue();
-
-if (DestSize < SourceSize)
-  Diagnose(FS.getArgIndex(), DestSize, SourceSize);
-
-return true;
-  }
-};
-
 class EstimateSizeFormatHandler
 : public analyze_format_string::FormatStringHandler {
   size_t Size;
@@ -670,12 +615,9 @@ void 
Sema::checkFortifiedBuiltinMemoryFunction(FunctionDecl *FD,
 // (potentially) more strict checking mode. Otherwise, conservatively 
assume
 // type 0.
 int BOSType = 0;
-// This check can fail for variadic functions.
-if (Index < FD->getNumParams()) {
-  if (const auto *POS =
-  FD->getParamDecl(Index)->getAttr())
-BOSType = POS->getType();
-}
+if (const auto *POS =
+FD->getParamDecl(Index)->getAttr())
+  BOSType = POS->getType();
 
 const Expr *ObjArg = TheCall->getArg(Index);
 uint64_t Result;
@@ -700,20 +642,6 @@ void 
Sema::checkFortifiedBuiltinMemoryFunction(FunctionDecl *FD,
   unsigned DiagID = 0;
   bool IsChkVariant = false;
 
-  auto GetFunctionName = [&]() {
-StringRef FunctionName = getASTContext().BuiltinInfo.getName(BuiltinID);
-// Skim off the details of whichever builtin was called to produce a better
-// diagnostic, as it's unlikely that the user wrote the __builtin
-// explicitly.
-if (IsChkVariant) {
-  FunctionName = FunctionName.drop_front(std::strlen("__builtin___"));
-  FunctionName = FunctionName.drop_back(std::strlen("_chk"));
-} else if (FunctionName.startswith("__builtin_")) {
-  FunctionName = FunctionName.drop_front(std::

[clang] 2db66f8 - [clang] Fortify warning for scanf calls with field width too big.

2021-11-08 Thread Michael Benfield via cfe-commits

Author: Michael Benfield
Date: 2021-11-08T17:43:51Z
New Revision: 2db66f8d48beeea835cb9a6940e25bc04ab5d941

URL: 
https://github.com/llvm/llvm-project/commit/2db66f8d48beeea835cb9a6940e25bc04ab5d941
DIFF: 
https://github.com/llvm/llvm-project/commit/2db66f8d48beeea835cb9a6940e25bc04ab5d941.diff

LOG: [clang] Fortify warning for scanf calls with field width too big.

Differential Revision: https://reviews.llvm.org/D111833

Added: 
clang/test/Sema/warn-fortify-scanf.c

Modified: 
clang/include/clang/Basic/DiagnosticSemaKinds.td
clang/lib/Sema/SemaChecking.cpp

Removed: 




diff  --git a/clang/include/clang/Basic/DiagnosticSemaKinds.td 
b/clang/include/clang/Basic/DiagnosticSemaKinds.td
index 3f887309825a5..76d4f9286d371 100644
--- a/clang/include/clang/Basic/DiagnosticSemaKinds.td
+++ b/clang/include/clang/Basic/DiagnosticSemaKinds.td
@@ -833,6 +833,10 @@ def warn_fortify_source_format_overflow : Warning<
   " but format string expands to at least %2">,
   InGroup;
 
+def warn_fortify_scanf_overflow : Warning<
+  "'%0' may overflow; destination buffer in argument %1 has size "
+  "%2, but the corresponding specifier may require size %3">,
+  InGroup;
 
 /// main()
 // static main() is not an error in C, just in C++.

diff  --git a/clang/lib/Sema/SemaChecking.cpp b/clang/lib/Sema/SemaChecking.cpp
index 172357be9d862..e7b2a118bdaf4 100644
--- a/clang/lib/Sema/SemaChecking.cpp
+++ b/clang/lib/Sema/SemaChecking.cpp
@@ -408,6 +408,64 @@ static bool SemaBuiltinCallWithStaticChain(Sema &S, 
CallExpr *BuiltinCall) {
 
 namespace {
 
+class ScanfDiagnosticFormatHandler
+: public analyze_format_string::FormatStringHandler {
+  // Accepts the argument index (relative to the first destination index) of 
the
+  // argument whose size we want.
+  using ComputeSizeFunction =
+  llvm::function_ref(unsigned)>;
+
+  // Accepts the argument index (relative to the first destination index), the
+  // destination size, and the source size).
+  using DiagnoseFunction =
+  llvm::function_ref;
+
+  ComputeSizeFunction ComputeSizeArgument;
+  DiagnoseFunction Diagnose;
+
+public:
+  ScanfDiagnosticFormatHandler(ComputeSizeFunction ComputeSizeArgument,
+   DiagnoseFunction Diagnose)
+  : ComputeSizeArgument(ComputeSizeArgument), Diagnose(Diagnose) {}
+
+  bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
+const char *StartSpecifier,
+unsigned specifierLen) override {
+if (!FS.consumesDataArgument())
+  return true;
+
+unsigned NulByte = 0;
+switch ((FS.getConversionSpecifier().getKind())) {
+default:
+  return true;
+case analyze_format_string::ConversionSpecifier::sArg:
+case analyze_format_string::ConversionSpecifier::ScanListArg:
+  NulByte = 1;
+  break;
+case analyze_format_string::ConversionSpecifier::cArg:
+  break;
+}
+
+auto OptionalFW = FS.getFieldWidth();
+if (OptionalFW.getHowSpecified() !=
+analyze_format_string::OptionalAmount::HowSpecified::Constant)
+  return true;
+
+unsigned SourceSize = OptionalFW.getConstantAmount() + NulByte;
+
+auto DestSizeAPS = ComputeSizeArgument(FS.getArgIndex());
+if (!DestSizeAPS)
+  return true;
+
+unsigned DestSize = DestSizeAPS->getZExtValue();
+
+if (DestSize < SourceSize)
+  Diagnose(FS.getArgIndex(), DestSize, SourceSize);
+
+return true;
+  }
+};
+
 class EstimateSizeFormatHandler
 : public analyze_format_string::FormatStringHandler {
   size_t Size;
@@ -615,9 +673,12 @@ void 
Sema::checkFortifiedBuiltinMemoryFunction(FunctionDecl *FD,
 // (potentially) more strict checking mode. Otherwise, conservatively 
assume
 // type 0.
 int BOSType = 0;
-if (const auto *POS =
-FD->getParamDecl(Index)->getAttr())
-  BOSType = POS->getType();
+// This check can fail for variadic functions.
+if (Index < FD->getNumParams()) {
+  if (const auto *POS =
+  FD->getParamDecl(Index)->getAttr())
+BOSType = POS->getType();
+}
 
 const Expr *ObjArg = TheCall->getArg(Index);
 uint64_t Result;
@@ -642,6 +703,20 @@ void 
Sema::checkFortifiedBuiltinMemoryFunction(FunctionDecl *FD,
   unsigned DiagID = 0;
   bool IsChkVariant = false;
 
+  auto GetFunctionName = [&]() {
+StringRef FunctionName = getASTContext().BuiltinInfo.getName(BuiltinID);
+// Skim off the details of whichever builtin was called to produce a better
+// diagnostic, as it's unlikely that the user wrote the __builtin
+// explicitly.
+if (IsChkVariant) {
+  FunctionName = FunctionName.drop_front(std::strlen("__builtin___"));
+  FunctionName = FunctionName.drop_back(std::strlen("_chk"));
+} else if (FunctionName.startswith("__builtin_")) {
+  FunctionName = FunctionName.drop_front(std::strlen("__builtin_"));
+}
+

[clang-tools-extra] 0ca5993 - [clang-tidy] Add option WarnOnSizeOfPointerToAggregate.

2022-09-22 Thread Michael Benfield via cfe-commits

Author: Michael Benfield
Date: 2022-09-22T17:09:43Z
New Revision: 0ca5993741877ab7fd27a251cbc1895bd092d5ee

URL: 
https://github.com/llvm/llvm-project/commit/0ca5993741877ab7fd27a251cbc1895bd092d5ee
DIFF: 
https://github.com/llvm/llvm-project/commit/0ca5993741877ab7fd27a251cbc1895bd092d5ee.diff

LOG: [clang-tidy] Add option WarnOnSizeOfPointerToAggregate.

This is now an option under the check bugprone-sizeof-expression.

Differential Revision: https://reviews.llvm.org/D134381

Added: 

clang-tools-extra/test/clang-tidy/checkers/bugprone/sizeof-expression-warn-on-sizeof-pointer-to-aggregate.cpp

Modified: 
clang-tools-extra/clang-tidy/bugprone/SizeofExpressionCheck.cpp
clang-tools-extra/clang-tidy/bugprone/SizeofExpressionCheck.h

Removed: 




diff  --git a/clang-tools-extra/clang-tidy/bugprone/SizeofExpressionCheck.cpp 
b/clang-tools-extra/clang-tidy/bugprone/SizeofExpressionCheck.cpp
index fe5c80658f268..57086af9c7031 100644
--- a/clang-tools-extra/clang-tidy/bugprone/SizeofExpressionCheck.cpp
+++ b/clang-tools-extra/clang-tidy/bugprone/SizeofExpressionCheck.cpp
@@ -67,7 +67,9 @@ SizeofExpressionCheck::SizeofExpressionCheck(StringRef Name,
   Options.get("WarnOnSizeOfIntegerExpression", false)),
   WarnOnSizeOfThis(Options.get("WarnOnSizeOfThis", true)),
   WarnOnSizeOfCompareToConstant(
-  Options.get("WarnOnSizeOfCompareToConstant", true)) {}
+  Options.get("WarnOnSizeOfCompareToConstant", true)),
+  WarnOnSizeOfPointerToAggregate(
+  Options.get("WarnOnSizeOfPointerToAggregate", true)) {}
 
 void SizeofExpressionCheck::storeOptions(ClangTidyOptions::OptionMap &Opts) {
   Options.store(Opts, "WarnOnSizeOfConstant", WarnOnSizeOfConstant);
@@ -76,6 +78,8 @@ void 
SizeofExpressionCheck::storeOptions(ClangTidyOptions::OptionMap &Opts) {
   Options.store(Opts, "WarnOnSizeOfThis", WarnOnSizeOfThis);
   Options.store(Opts, "WarnOnSizeOfCompareToConstant",
 WarnOnSizeOfCompareToConstant);
+  Options.store(Opts, "WarnOnSizeOfPointerToAggregate",
+WarnOnSizeOfPointerToAggregate);
 }
 
 void SizeofExpressionCheck::registerMatchers(MatchFinder *Finder) {
@@ -135,46 +139,48 @@ void SizeofExpressionCheck::registerMatchers(MatchFinder 
*Finder) {
 
   // Detect sizeof(ptr) where ptr points to an aggregate (i.e. sizeof(&S)).
   // Do not find it if RHS of a 'sizeof(arr) / sizeof(arr[0])' expression.
-  const auto ArrayExpr =
-  ignoringParenImpCasts(hasType(hasCanonicalType(arrayType(;
-  const auto ArrayCastExpr = expr(anyOf(
-  unaryOperator(hasUnaryOperand(ArrayExpr), unless(hasOperatorName("*"))),
-  binaryOperator(hasEitherOperand(ArrayExpr)),
-  castExpr(hasSourceExpression(ArrayExpr;
-  const auto PointerToArrayExpr = ignoringParenImpCasts(
-  hasType(hasCanonicalType(pointerType(pointee(arrayType());
-
-  const auto StructAddrOfExpr = unaryOperator(
-  hasOperatorName("&"), hasUnaryOperand(ignoringParenImpCasts(
-hasType(hasCanonicalType(recordType());
-  const auto PointerToStructType =
-  hasUnqualifiedDesugaredType(pointerType(pointee(recordType(;
-  const auto PointerToStructExpr = ignoringParenImpCasts(expr(
-  hasType(hasCanonicalType(PointerToStructType)), unless(cxxThisExpr(;
-
-  const auto ArrayOfPointersExpr = ignoringParenImpCasts(
-  hasType(hasCanonicalType(arrayType(hasElementType(pointerType()))
-   .bind("type-of-array-of-pointers";
-  const auto ArrayOfSamePointersExpr =
-  ignoringParenImpCasts(hasType(hasCanonicalType(
-  arrayType(equalsBoundNode("type-of-array-of-pointers");
-  const auto ZeroLiteral = ignoringParenImpCasts(integerLiteral(equals(0)));
-  const auto ArrayOfSamePointersZeroSubscriptExpr =
-  
ignoringParenImpCasts(arraySubscriptExpr(hasBase(ArrayOfSamePointersExpr),
-   hasIndex(ZeroLiteral)));
-  const auto ArrayLengthExprDenom =
-  expr(hasParent(expr(ignoringParenImpCasts(binaryOperator(
-   hasOperatorName("/"), hasLHS(ignoringParenImpCasts(sizeOfExpr(
- has(ArrayOfPointersExpr,
-   sizeOfExpr(has(ArrayOfSamePointersZeroSubscriptExpr)));
-
-  Finder->addMatcher(expr(anyOf(sizeOfExpr(has(ignoringParenImpCasts(anyOf(
-ArrayCastExpr, PointerToArrayExpr,
-StructAddrOfExpr, PointerToStructExpr,
-sizeOfExpr(has(PointerToStructType))),
-  unless(ArrayLengthExprDenom))
- .bind("sizeof-pointer-to-aggregate"),
- this);
+  if (WarnOnSizeOfPointerToAggregate) {
+const auto ArrayExpr =
+ignoringParenImpCasts(hasType(hasCanonicalType(arrayType(;
+const auto Arra

[clang-tools-extra] 33bc9c3 - Document WarnOnSizeOfPointerToAggregate.

2022-09-22 Thread Michael Benfield via cfe-commits

Author: Michael Benfield
Date: 2022-09-22T17:38:04Z
New Revision: 33bc9c3bf2e09f15ea7be7bc090492fad8226b34

URL: 
https://github.com/llvm/llvm-project/commit/33bc9c3bf2e09f15ea7be7bc090492fad8226b34
DIFF: 
https://github.com/llvm/llvm-project/commit/33bc9c3bf2e09f15ea7be7bc090492fad8226b34.diff

LOG: Document WarnOnSizeOfPointerToAggregate.

This option was just landed in D134381. It would make sense to actually
document it.

Differential Revision: https://reviews.llvm.org/D134457

Added: 


Modified: 
clang-tools-extra/docs/clang-tidy/checks/bugprone/sizeof-expression.rst

Removed: 




diff  --git 
a/clang-tools-extra/docs/clang-tidy/checks/bugprone/sizeof-expression.rst 
b/clang-tools-extra/docs/clang-tidy/checks/bugprone/sizeof-expression.rst
index 4ba7c3008bd6a..a3e88b837d375 100644
--- a/clang-tools-extra/docs/clang-tidy/checks/bugprone/sizeof-expression.rst
+++ b/clang-tools-extra/docs/clang-tidy/checks/bugprone/sizeof-expression.rst
@@ -187,3 +187,9 @@ Options
When `true`, the check will warn on an expression like
``sizeof(expr) <= k`` for a suspicious constant `k` while `k` is `0` or
greater than `0x8000`. Default is `true`.
+
+.. option:: WarnOnSizeOfPointerToAggregate
+
+   When `true, the check will warn on an expression like
+   ``sizeof(expr)`` where the expression is a pointer
+   to aggregate. Default is `true`.



___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] bc5f2d1 - [clang] diagnose_as_builtin attribute for Fortify diagnosing like builtins.

2021-12-14 Thread Michael Benfield via cfe-commits

Author: Michael Benfield
Date: 2021-12-14T19:42:23Z
New Revision: bc5f2d12cadce765620efc56a1ca815221db47af

URL: 
https://github.com/llvm/llvm-project/commit/bc5f2d12cadce765620efc56a1ca815221db47af
DIFF: 
https://github.com/llvm/llvm-project/commit/bc5f2d12cadce765620efc56a1ca815221db47af.diff

LOG: [clang] diagnose_as_builtin attribute for Fortify diagnosing like builtins.

Differential Revision: https://reviews.llvm.org/D112024

Added: 
clang/test/Sema/attr-diagnose-as-builtin.c

Modified: 
clang/include/clang/Basic/Attr.td
clang/include/clang/Basic/AttrDocs.td
clang/include/clang/Basic/DiagnosticSemaKinds.td
clang/include/clang/Sema/ParsedAttr.h
clang/lib/Sema/SemaChecking.cpp
clang/lib/Sema/SemaDeclAttr.cpp
clang/test/Misc/pragma-attribute-supported-attributes-list.test

Removed: 




diff  --git a/clang/include/clang/Basic/Attr.td 
b/clang/include/clang/Basic/Attr.td
index fab3f3edfb831..10c5c7f1b879a 100644
--- a/clang/include/clang/Basic/Attr.td
+++ b/clang/include/clang/Basic/Attr.td
@@ -3865,6 +3865,14 @@ def ReleaseHandle : InheritableParamAttr {
   let Documentation = [ReleaseHandleDocs];
 }
 
+def DiagnoseAsBuiltin : InheritableAttr {
+  let Spellings = [Clang<"diagnose_as_builtin">];
+  let Args = [DeclArgument,
+  VariadicUnsignedArgument<"ArgIndices">];
+  let Subjects = SubjectList<[Function]>;
+  let Documentation = [DiagnoseAsBuiltinDocs];
+}
+
 def Builtin : InheritableAttr {
   let Spellings = [];
   let Args = [UnsignedArgument<"ID">];

diff  --git a/clang/include/clang/Basic/AttrDocs.td 
b/clang/include/clang/Basic/AttrDocs.td
index b005284eb492e..8a7424a88c9f8 100644
--- a/clang/include/clang/Basic/AttrDocs.td
+++ b/clang/include/clang/Basic/AttrDocs.td
@@ -5984,6 +5984,50 @@ attribute requires a string literal argument to identify 
the handle being releas
   }];
 }
 
+def DiagnoseAsBuiltinDocs : Documentation {
+  let Category = DocCatFunction;
+  let Content = [{
+The ``diagnose_as_builtin` attribute indicates that Fortify diagnostics are to
+be applied to the declared function as if it were the function specified by the
+attribute. The builtin function whose diagnostics are to be mimicked should be
+given. In addition, the order in which arguments should be applied must also
+be given.
+
+For example, the attribute can be used as follows.
+
+  .. code-block:: c
+
+__attribute__((diagnose_as_builtin(__builtin_memset, 3, 2, 1)))
+void *mymemset(int n, int c, void *s) {
+  // ...
+}
+
+This indicates that calls to ``mymemset`` should be diagnosed as if they were
+calls to ``__builtin_memset``. The arguments ``3, 2, 1`` indicate by index the
+order in which arguments of ``mymemset`` should be applied to
+``__builtin_memset``. The third argument should be applied first, then the
+second, and then the first. Thus (when Fortify warnings are enabled) the call
+``mymemset(n, c, s)`` will diagnose overflows as if it were the call
+``__builtin_memset(s, c, n)``.
+
+For variadic functions, the variadic arguments must come in the same order as
+they would to the builtin function, after all normal arguments. For instance,
+to diagnose a new function as if it were `sscanf`, we can use the attribute as
+follows.
+
+  .. code-block:: c
+  __attribute__((diagnose_as_builtin(sscanf, 1, 2)))
+  int mysscanf(const char *str, const char *format, ...)  {
+// ...
+  }
+
+Then the call `mysscanf("abc def", "%4s %4s", buf1, buf2)` will be diagnosed as
+if it were the call `sscanf("abc def", "%4s %4s", buf1, buf2)`.
+
+This attribute cannot be applied to non-static member functions.
+}];
+}
+
 def ArmSveVectorBitsDocs : Documentation {
   let Category = DocCatType;
   let Content = [{

diff  --git a/clang/include/clang/Basic/DiagnosticSemaKinds.td 
b/clang/include/clang/Basic/DiagnosticSemaKinds.td
index 29d389ee0b0d7..038067521559c 100644
--- a/clang/include/clang/Basic/DiagnosticSemaKinds.td
+++ b/clang/include/clang/Basic/DiagnosticSemaKinds.td
@@ -2956,6 +2956,17 @@ def err_attribute_invalid_argument : Error<
 def err_attribute_wrong_number_arguments : Error<
   "%0 attribute %plural{0:takes no arguments|1:takes one argument|"
   ":requires exactly %1 arguments}1">;
+def err_attribute_wrong_number_arguments_for : Error <
+  "%0 attribute references function %1, which %plural{0:takes no 
arguments|1:takes one argument|"
+  ":takes exactly %2 arguments}2">;
+def err_attribute_bounds_for_function : Error<
+  "%0 attribute references parameter %1, but the function %2 has only %3 
parameters">;
+def err_attribute_no_member_function : Error<
+  "%0 attribute cannot be applied to non-static member functions">;
+def err_attribute_parameter_types : Error<
+  "%0 attribute parameter types do not match: parameter %1 of function %2 has 
type %3, "
+  "but parameter %4 of function %5 has type %6">;
+
 def err_attribute_too_many_arguments : Error<
   "%0 attribute takes

[clang] 89aa87c - [clang] Fix AttrDocs.td formatting.

2021-12-28 Thread Michael Benfield via cfe-commits

Author: Michael Benfield
Date: 2021-12-28T19:13:03Z
New Revision: 89aa87c4e601985dae4b41206f0c5594e8742c78

URL: 
https://github.com/llvm/llvm-project/commit/89aa87c4e601985dae4b41206f0c5594e8742c78
DIFF: 
https://github.com/llvm/llvm-project/commit/89aa87c4e601985dae4b41206f0c5594e8742c78.diff

LOG: [clang] Fix AttrDocs.td formatting.

This should fix the builder clang-sphinx-docs.

Added: 


Modified: 
clang/include/clang/Basic/AttrDocs.td

Removed: 




diff  --git a/clang/include/clang/Basic/AttrDocs.td 
b/clang/include/clang/Basic/AttrDocs.td
index 8a7424a88c9f8..a24218a9c82b6 100644
--- a/clang/include/clang/Basic/AttrDocs.td
+++ b/clang/include/clang/Basic/AttrDocs.td
@@ -5987,7 +5987,7 @@ attribute requires a string literal argument to identify 
the handle being releas
 def DiagnoseAsBuiltinDocs : Documentation {
   let Category = DocCatFunction;
   let Content = [{
-The ``diagnose_as_builtin` attribute indicates that Fortify diagnostics are to
+The ``diagnose_as_builtin`` attribute indicates that Fortify diagnostics are to
 be applied to the declared function as if it were the function specified by the
 attribute. The builtin function whose diagnostics are to be mimicked should be
 given. In addition, the order in which arguments should be applied must also
@@ -5995,12 +5995,12 @@ be given.
 
 For example, the attribute can be used as follows.
 
-  .. code-block:: c
+.. code-block:: c
 
-__attribute__((diagnose_as_builtin(__builtin_memset, 3, 2, 1)))
-void *mymemset(int n, int c, void *s) {
-  // ...
-}
+  __attribute__((diagnose_as_builtin(__builtin_memset, 3, 2, 1)))
+  void *mymemset(int n, int c, void *s) {
+// ...
+  }
 
 This indicates that calls to ``mymemset`` should be diagnosed as if they were
 calls to ``__builtin_memset``. The arguments ``3, 2, 1`` indicate by index the
@@ -6015,7 +6015,8 @@ they would to the builtin function, after all normal 
arguments. For instance,
 to diagnose a new function as if it were `sscanf`, we can use the attribute as
 follows.
 
-  .. code-block:: c
+.. code-block:: c
+
   __attribute__((diagnose_as_builtin(sscanf, 1, 2)))
   int mysscanf(const char *str, const char *format, ...)  {
 // ...



___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits