[clang-tools-extra] [clang-tidy] Add user-defined functions to `bugprone-unsafe-functions` check (PR #106350)

Julian Schmidt via cfe-commits cfe-commits at lists.llvm.org
Thu Aug 29 09:20:50 PDT 2024


================
@@ -186,16 +298,62 @@ void UnsafeFunctionsCheck::check(const MatchFinder::MatchResult &Result) {
   const auto *FuncDecl = cast<FunctionDecl>(DeclRef->getDecl());
   assert(DeclRef && FuncDecl && "No valid matched node in check()");
 
+  // Only one of these are matched at a time.
   const auto *AnnexK = Result.Nodes.getNodeAs<FunctionDecl>(
       FunctionNamesWithAnnexKReplacementId);
   const auto *Normal = Result.Nodes.getNodeAs<FunctionDecl>(FunctionNamesId);
   const auto *Additional =
       Result.Nodes.getNodeAs<FunctionDecl>(AdditionalFunctionNamesId);
-  assert((AnnexK || Normal || Additional) && "No valid match category.");
+  const auto *CustomAnnexK =
+      Result.Nodes.getNodeAs<FunctionDecl>(CustomAnnexKFunctionNamesId);
+  const auto *CustomNormal =
+      Result.Nodes.getNodeAs<FunctionDecl>(CustomFunctionNamesId);
+  assert((AnnexK || Normal || Additional || CustomAnnexK || CustomNormal) &&
+         "No valid match category.");
 
   bool AnnexKIsAvailable =
       isAnnexKAvailable(IsAnnexKAvailable, PP, getLangOpts());
   StringRef FunctionName = FuncDecl->getName();
+
+  if (CustomAnnexK || CustomNormal) {
+    const auto ShowCheckedFunctionWarning = [&](const CheckedFunction &Entry) {
+      StringRef Reason =
+          Entry.Reason.empty() ? "is marked as unsafe" : Entry.Reason.c_str();
+      diag(DeclRef->getExprLoc(), "function %0 %1; '%2' should be used instead")
+          << FuncDecl << Reason << Entry.Replacement
+          << DeclRef->getSourceRange();
+    };
+
+    if (AnnexKIsAvailable) {
+      for (const auto &Entry : CustomAnnexKFunctions) {
+        if (Entry.Pattern.match(*FuncDecl)) {
+          // If both Annex K and Normal are matched, show Annex K warning only.
+          if (CustomAnnexK)
+            ShowCheckedFunctionWarning(Entry);
+
+          return;
+        }
+      }
+
+      assert(!CustomAnnexK && "No custom Annex K function was matched.");
+    }
+
+    // Annex K was not available, or the assertion failed.
+    if (CustomAnnexK)
+      return;
+
+    for (const auto &Entry : CustomNormalFunctions) {
+
+      if (Entry.Pattern.match(*FuncDecl)) {
+        ShowCheckedFunctionWarning(Entry);
+        return;
+      }
+    }
+
+    assert(false && "No custom function was matched.");
----------------
5chmidti wrote:

nit: use `llvm_unreachable` instead? (same with "No valid match category.")

https://github.com/llvm/llvm-project/pull/106350


More information about the cfe-commits mailing list