juliehockett updated this revision to Diff 145547.
juliehockett marked 9 inline comments as done.
juliehockett edited the summary of this revision.
juliehockett added a comment.

Sorry for the delay in updating this -- check now restricts includes to a 
whitelist, rather than a blacklist, and only applies to system headers, to more 
strictly control which are allowed.

Also updated warning text and addressed comments.


https://reviews.llvm.org/D43778

Files:
  clang-tidy/fuchsia/CMakeLists.txt
  clang-tidy/fuchsia/FuchsiaTidyModule.cpp
  clang-tidy/fuchsia/RestrictIncludesCheck.cpp
  clang-tidy/fuchsia/RestrictIncludesCheck.h
  docs/ReleaseNotes.rst
  docs/clang-tidy/checks/fuchsia-restrict-includes.rst
  docs/clang-tidy/checks/list.rst
  test/clang-tidy/Inputs/fuchsia-restrict-includes/a.h
  test/clang-tidy/Inputs/fuchsia-restrict-includes/b.h
  test/clang-tidy/Inputs/fuchsia-restrict-includes/system/j.h
  test/clang-tidy/Inputs/fuchsia-restrict-includes/system/r.h
  test/clang-tidy/Inputs/fuchsia-restrict-includes/system/s.h
  test/clang-tidy/Inputs/fuchsia-restrict-includes/system/t.h
  test/clang-tidy/Inputs/fuchsia-restrict-includes/system/transitive.h
  test/clang-tidy/fuchsia-restrict-includes.cpp

Index: test/clang-tidy/fuchsia-restrict-includes.cpp
===================================================================
--- /dev/null
+++ test/clang-tidy/fuchsia-restrict-includes.cpp
@@ -0,0 +1,30 @@
+// RUN: %check_clang_tidy %s fuchsia-restrict-includes %t \
+// RUN:		-- -config="{CheckOptions: [{key: fuchsia-restrict-includes.Includes, value: 's.h;transitive.h'}]}" \
+// RUN:   -system-headers -header-filter=.* \
+// RUN:   -- -std=c++11 -I %S/Inputs/fuchsia-restrict-includes -isystem %S/Inputs/fuchsia-restrict-includes/system
+
+#include "a.h"
+
+#include <t.h>
+// CHECK-MESSAGES: :[[@LINE-1]]:1: warning: system include t.h not allowed
+// CHECK-FIXES-NOT: #include <t.h>
+#include <s.h>
+
+#define foo <j.h>
+
+#include foo
+// CHECK-MESSAGES: :[[@LINE-1]]:1: warning: system include j.h not allowed
+// CHECK-FIXES-NOT: #include foo
+
+#/* comment */ include /* comment */ foo
+// CHECK-MESSAGES: :[[@LINE-1]]:1: warning: system include j.h not allowed
+// CHECK-FIXES-NOT: # /* comment */ include /* comment */ foo
+
+// transitive.h includes <r.h>
+#include <transitive.h>
+// CHECK-MESSAGES: :1:1: warning: system include r.h not allowed, transitively included from {{(.*\/)}}Inputs/fuchsia-restrict-includes/system/transitive.h
+
+int main() {
+  // f() is declared in r.h
+  f();
+}
\ No newline at end of file
Index: test/clang-tidy/Inputs/fuchsia-restrict-includes/system/transitive.h
===================================================================
--- /dev/null
+++ test/clang-tidy/Inputs/fuchsia-restrict-includes/system/transitive.h
@@ -0,0 +1 @@
+#include <r.h>
\ No newline at end of file
Index: test/clang-tidy/Inputs/fuchsia-restrict-includes/system/r.h
===================================================================
--- /dev/null
+++ test/clang-tidy/Inputs/fuchsia-restrict-includes/system/r.h
@@ -0,0 +1 @@
+void f() {}
\ No newline at end of file
Index: docs/clang-tidy/checks/list.rst
===================================================================
--- docs/clang-tidy/checks/list.rst
+++ docs/clang-tidy/checks/list.rst
@@ -95,6 +95,7 @@
    fuchsia-default-arguments
    fuchsia-multiple-inheritance
    fuchsia-overloaded-operator
+   fuchsia-restrict-includes
    fuchsia-statically-constructed-objects
    fuchsia-trailing-return
    fuchsia-virtual-inheritance
Index: docs/clang-tidy/checks/fuchsia-restrict-includes.rst
===================================================================
--- /dev/null
+++ docs/clang-tidy/checks/fuchsia-restrict-includes.rst
@@ -0,0 +1,31 @@
+.. title:: clang-tidy - fuchsia-restrict-includes
+
+fuchsia-restrict-includes
+=========================
+
+Checks for allowed includes and suggests removal of any others. If no includes
+are specified, the check will exit without issuing any warnings. 
+
+It is important to note that running this check with fixes may break code, as
+the fix removes headers.
+
+Note that the separator for identifying allowed includes is a semi-colon, and
+therefore this check is unable to allow an include with a semi-colon in the
+filename (e.g. 'foo;bar.h' will be parsed as allowing 'foo' and 'bar.h', and not
+as allowing a file called 'foo;bar.h').
+
+For example, given the allowed system includes 'a.h; b.h':
+
+.. code-block:: c++
+
+  #include <a.h>
+  #include <b.h>
+  #include <c.h>    // Warning, as c.h is not explicitly allowed
+  
+Options
+-------
+
+.. option:: Includes
+
+   A string containing a semi-colon separated list of allowed include filenames.
+   The default is an empty string, which allows all includes.
Index: docs/ReleaseNotes.rst
===================================================================
--- docs/ReleaseNotes.rst
+++ docs/ReleaseNotes.rst
@@ -110,8 +110,14 @@
   Checks whether a ``std::string::find()`` result is compared with 0, and
   suggests replacing with ``absl::StartsWith()``.
 
-- New :doc:`fuchsia-statically-constructed-objects
-  <clang-tidy/checks/fuchsia-statically-constructed-objects>` check.
+- New `fuchsia-restrict-includes
+  <http://clang.llvm.org/extra/clang-tidy/checks/fuchsia-restrict-includes.html>`_ check
+
+  Checks for allowed includes and suggests removal of any others. If no includes
+  are specified, the check will exit without issuing any warnings.
+
+- New `fuchsia-statically-constructed-objects
+  <http://clang.llvm.org/extra/clang-tidy/checks/fuchsia-statically-constructed-objects.html>`_ check
 
   Warns if global, non-trivial objects with static storage are constructed,
   unless the object is statically initialized with a ``constexpr`` constructor
Index: clang-tidy/fuchsia/RestrictIncludesCheck.h
===================================================================
--- /dev/null
+++ clang-tidy/fuchsia/RestrictIncludesCheck.h
@@ -0,0 +1,46 @@
+//===--- RestrictIncludesCheck.h - clang-tidy---------------------*- C++-*-===//
+//
+//                     The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_FUCHSIA_RESTRICTINCLUDESSCHECK_H
+#define LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_FUCHSIA_RESTRICTINCLUDESSCHECK_H
+
+#include "../ClangTidy.h"
+#include "../utils/OptionsUtils.h"
+
+namespace clang {
+namespace tidy {
+namespace fuchsia {
+
+/// Checks for allowed includes and suggests removal of any others. If no
+/// includes are specified, the check will exit without issuing any warnings.
+///
+/// For the user-facing documentation see:
+/// http://clang.llvm.org/extra/clang-tidy/checks/fuchsia-restrict-includes.html
+class RestrictIncludesCheck : public ClangTidyCheck {
+public:
+  RestrictIncludesCheck(StringRef Name, ClangTidyContext *Context)
+      : ClangTidyCheck(Name, Context),
+        AllowedIncludes(
+            utils::options::parseStringList(Options.get("Includes", ""))) {}
+
+  void registerPPCallbacks(CompilerInstance &Compiler) override;
+  void storeOptions(ClangTidyOptions::OptionMap &Opts) override;
+  const std::vector<std::string> &getAllowedIncludes() const {
+    return AllowedIncludes;
+  }
+
+private:
+  std::vector<std::string> AllowedIncludes;
+};
+
+} // namespace fuchsia
+} // namespace tidy
+} // namespace clang
+
+#endif // LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_FUCHSIA_RESTRICTINCLUDESSCHECK_H
Index: clang-tidy/fuchsia/RestrictIncludesCheck.cpp
===================================================================
--- /dev/null
+++ clang-tidy/fuchsia/RestrictIncludesCheck.cpp
@@ -0,0 +1,115 @@
+//===--- RestrictIncludesCheck.cpp - clang-tidy----------------------------===//
+//
+//                     The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+
+#include "RestrictIncludesCheck.h"
+#include "clang/Frontend/CompilerInstance.h"
+#include "clang/Lex/PPCallbacks.h"
+#include "clang/Lex/Preprocessor.h"
+#include "llvm/ADT/DenseMap.h"
+#include "llvm/ADT/SmallVector.h"
+#include <cstring>
+
+namespace clang {
+namespace tidy {
+namespace fuchsia {
+
+class RestrictedIncludesPPCallbacks : public PPCallbacks {
+public:
+  explicit RestrictedIncludesPPCallbacks(RestrictIncludesCheck &Check,
+                                         SourceManager &SM)
+      : Check(Check), SM(SM) {}
+
+  void InclusionDirective(SourceLocation HashLoc, const Token &IncludeTok,
+                          StringRef FileName, bool IsAngled,
+                          CharSourceRange FilenameRange, const FileEntry *File,
+                          StringRef SearchPath, StringRef RelativePath,
+                          const Module *Imported) override;
+  void EndOfMainFile() override;
+
+private:
+  struct IncludeDirective {
+    IncludeDirective() = default;
+    IncludeDirective(SourceLocation Loc, CharSourceRange Range,
+                     StringRef Filename, bool IsInMainFile)
+        : Loc(Loc), Range(Range), IncludeFile(Filename),
+          IsInMainFile(IsInMainFile) {}
+
+    SourceLocation Loc;      // '#' location in the include directive
+    CharSourceRange Range;   // SourceRange for the file name
+    std::string IncludeFile; // Filename as a string
+    bool IsInMainFile;       // Whether or not the include is in the main file
+  };
+
+  using FileIncludes = llvm::SmallVector<IncludeDirective, 8>;
+  llvm::SmallDenseMap<FileID, FileIncludes> IncludeDirectives;
+
+  RestrictIncludesCheck &Check;
+  SourceManager &SM;
+};
+
+void RestrictedIncludesPPCallbacks::InclusionDirective(
+    SourceLocation HashLoc, const Token &IncludeTok, StringRef FileName,
+    bool IsAngled, CharSourceRange FilenameRange, const FileEntry *File,
+    StringRef SearchPath, StringRef RelativePath, const Module *Imported) {
+  if (!llvm::is_contained(Check.getAllowedIncludes(), FileName) && IsAngled)
+    // Bucket the allowed include directives by the id of the file they were
+    // declared in.
+    IncludeDirectives[SM.getFileID(HashLoc)].emplace_back(
+        HashLoc, FilenameRange, FileName, SM.isInMainFile(HashLoc));
+}
+
+void RestrictedIncludesPPCallbacks::EndOfMainFile() {
+  if (IncludeDirectives.empty())
+    return;
+
+  for (const auto &Bucket : IncludeDirectives) {
+    const FileIncludes &FileDirectives = Bucket.second;
+
+    // Emit fixits for all restricted includes.
+    for (const auto &Include : FileDirectives) {
+      // If we're in a header file, no fix is issued.
+      if (!Include.IsInMainFile) {
+        Check.diag(
+            Include.Loc,
+            "system include %0 not allowed, transitively included from %1")
+            << Include.IncludeFile << SM.getFilename(Include.Loc);
+        return;
+      }
+
+      auto D = Check.diag(Include.Loc, "system include %0 not allowed");
+      D << Include.IncludeFile;
+
+      // Fetch the length of the include statement from the start to just after
+      // the newline, for finding the end (including the newline).
+      unsigned ToLen = std::strcspn(SM.getCharacterData(Include.Loc), "\n") + 1;
+      CharSourceRange ToRange = CharSourceRange::getCharRange(
+          Include.Loc, Include.Loc.getLocWithOffset(ToLen));
+
+      D << FixItHint::CreateRemoval(ToRange);
+    }
+  }
+}
+
+void RestrictIncludesCheck::registerPPCallbacks(CompilerInstance &Compiler) {
+  // Do nothing if there are no restricted includes.
+  if (AllowedIncludes.empty())
+    return;
+  Compiler.getPreprocessor().addPPCallbacks(
+      llvm::make_unique<RestrictedIncludesPPCallbacks>(
+          *this, Compiler.getSourceManager()));
+}
+
+void RestrictIncludesCheck::storeOptions(ClangTidyOptions::OptionMap &Opts) {
+  Options.store(Opts, "Includes",
+                utils::options::serializeStringList(AllowedIncludes));
+}
+
+} // namespace fuchsia
+} // namespace tidy
+} // namespace clang
Index: clang-tidy/fuchsia/FuchsiaTidyModule.cpp
===================================================================
--- clang-tidy/fuchsia/FuchsiaTidyModule.cpp
+++ clang-tidy/fuchsia/FuchsiaTidyModule.cpp
@@ -14,6 +14,7 @@
 #include "DefaultArgumentsCheck.h"
 #include "MultipleInheritanceCheck.h"
 #include "OverloadedOperatorCheck.h"
+#include "RestrictIncludesCheck.h"
 #include "StaticallyConstructedObjectsCheck.h"
 #include "TrailingReturnCheck.h"
 #include "VirtualInheritanceCheck.h"
@@ -36,6 +37,8 @@
         "fuchsia-multiple-inheritance");
     CheckFactories.registerCheck<OverloadedOperatorCheck>(
         "fuchsia-overloaded-operator");
+    CheckFactories.registerCheck<RestrictIncludesCheck>(
+        "fuchsia-restrict-includes");
     CheckFactories.registerCheck<StaticallyConstructedObjectsCheck>(
         "fuchsia-statically-constructed-objects");
     CheckFactories.registerCheck<TrailingReturnCheck>(
Index: clang-tidy/fuchsia/CMakeLists.txt
===================================================================
--- clang-tidy/fuchsia/CMakeLists.txt
+++ clang-tidy/fuchsia/CMakeLists.txt
@@ -5,6 +5,7 @@
   FuchsiaTidyModule.cpp
   MultipleInheritanceCheck.cpp
   OverloadedOperatorCheck.cpp
+  RestrictIncludesCheck.cpp
   StaticallyConstructedObjectsCheck.cpp
   TrailingReturnCheck.cpp
   VirtualInheritanceCheck.cpp
_______________________________________________
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits

Reply via email to