Clang Project

clang_source_code/include/clang/StaticAnalyzer/Frontend/CheckerRegistry.h
1//===- CheckerRegistry.h - Maintains all available checkers -----*- C++ -*-===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8
9#ifndef LLVM_CLANG_STATICANALYZER_CORE_CHECKERREGISTRY_H
10#define LLVM_CLANG_STATICANALYZER_CORE_CHECKERREGISTRY_H
11
12#include "clang/Basic/LLVM.h"
13#include "clang/StaticAnalyzer/Core/CheckerManager.h"
14#include "llvm/ADT/StringMap.h"
15#include "llvm/ADT/StringRef.h"
16#include <cstddef>
17#include <vector>
18
19// FIXME: move this information to an HTML file in docs/.
20// At the very least, a checker plugin is a dynamic library that exports
21// clang_analyzerAPIVersionString. This should be defined as follows:
22//
23//   extern "C"
24//   const char clang_analyzerAPIVersionString[] =
25//     CLANG_ANALYZER_API_VERSION_STRING;
26//
27// This is used to check whether the current version of the analyzer is known to
28// be incompatible with a plugin. Plugins with incompatible version strings,
29// or without a version string at all, will not be loaded.
30//
31// To add a custom checker to the analyzer, the plugin must also define the
32// function clang_registerCheckers. For example:
33//
34//    extern "C"
35//    void clang_registerCheckers (CheckerRegistry &registry) {
36//      registry.addChecker<MainCallChecker>("example.MainCallChecker",
37//        "Disallows calls to functions called main");
38//    }
39//
40// The first method argument is the full name of the checker, including its
41// enclosing package. By convention, the registered name of a checker is the
42// name of the associated class (the template argument).
43// The second method argument is a short human-readable description of the
44// checker.
45//
46// The clang_registerCheckers function may add any number of checkers to the
47// registry. If any checkers require additional initialization, use the three-
48// argument form of CheckerRegistry::addChecker.
49//
50// To load a checker plugin, specify the full path to the dynamic library as
51// the argument to the -load option in the cc1 frontend. You can then enable
52// your custom checker using the -analyzer-checker:
53//
54//   clang -cc1 -load </path/to/plugin.dylib> -analyze
55//     -analyzer-checker=<example.MainCallChecker>
56//
57// For a complete working example, see examples/analyzer-plugin.
58
59#ifndef CLANG_ANALYZER_API_VERSION_STRING
60// FIXME: The Clang version string is not particularly granular;
61// the analyzer infrastructure can change a lot between releases.
62// Unfortunately, this string has to be statically embedded in each plugin,
63// so we can't just use the functions defined in Version.h.
64#include "clang/Basic/Version.h"
65#define CLANG_ANALYZER_API_VERSION_STRING CLANG_VERSION_STRING
66#endif
67
68namespace clang {
69
70class AnalyzerOptions;
71class DiagnosticsEngine;
72class LangOptions;
73
74namespace ento {
75
76/// Manages a set of available checkers for running a static analysis.
77/// The checkers are organized into packages by full name, where including
78/// a package will recursively include all subpackages and checkers within it.
79/// For example, the checker "core.builtin.NoReturnFunctionChecker" will be
80/// included if initializeManager() is called with an option of "core",
81/// "core.builtin", or the full name "core.builtin.NoReturnFunctionChecker".
82class CheckerRegistry {
83public:
84  CheckerRegistry(
85      ArrayRef<std::stringpluginsDiagnosticsEngine &diags,
86      AnalyzerOptions &AnOptsconst LangOptions &LangOpts,
87      ArrayRef<std::function<void(CheckerRegistry &)>>
88          checkerRegistrationFns = {});
89
90  /// Initialization functions perform any necessary setup for a checker.
91  /// They should include a call to CheckerManager::registerChecker.
92  using InitializationFunction = void (*)(CheckerManager &);
93  using ShouldRegisterFunction = bool (*)(const LangOptions &);
94
95  struct CheckerInfo;
96
97  using CheckerInfoList = std::vector<CheckerInfo>;
98  using CheckerInfoListRange = llvm::iterator_range<CheckerInfoList::iterator>;
99  using ConstCheckerInfoList = llvm::SmallVector<const CheckerInfo *, 0>;
100  using CheckerInfoSet = llvm::SetVector<const CheckerInfo *>;
101
102  struct CheckerInfo {
103    enum class StateFromCmdLine {
104      // This checker wasn't explicitly enabled or disabled.
105      State_Unspecified,
106      // This checker was explicitly disabled.
107      State_Disabled,
108      // This checker was explicitly enabled.
109      State_Enabled
110    };
111
112    InitializationFunction Initialize;
113    ShouldRegisterFunction ShouldRegister;
114    StringRef FullName;
115    StringRef Desc;
116    StringRef DocumentationUri;
117    StateFromCmdLine State = StateFromCmdLine::State_Unspecified;
118
119    ConstCheckerInfoList Dependencies;
120
121    bool isEnabled(const LangOptions &LOconst {
122      return State == StateFromCmdLine::State_Enabled && ShouldRegister(LO);
123    }
124
125    bool isDisabled(const LangOptions &LOconst {
126      return State == StateFromCmdLine::State_Disabled && ShouldRegister(LO);
127    }
128
129    CheckerInfo(InitializationFunction FnShouldRegisterFunction sfn,
130                StringRef NameStringRef DescStringRef DocsUri)
131        : Initialize(Fn), ShouldRegister(sfn), FullName(Name), Desc(Desc),
132          DocumentationUri(DocsUri) {}
133  };
134
135  using StateFromCmdLine = CheckerInfo::StateFromCmdLine;
136
137private:
138  template <typename T>
139  static void initializeManager(CheckerManager &mgr) {
140    mgr.registerChecker<T>();
141  }
142
143
144  template <typename T>
145  static bool returnTrue(const LangOptions &LO) {
146    return true;
147  }
148
149public:
150  /// Adds a checker to the registry. Use this non-templated overload when your
151  /// checker requires custom initialization.
152  void addChecker(InitializationFunction FnShouldRegisterFunction sfn,
153                  StringRef FullNameStringRef DescStringRef DocsUri);
154
155  /// Adds a checker to the registry. Use this templated overload when your
156  /// checker does not require any custom initialization.
157  template <class T>
158  void addChecker(StringRef FullNameStringRef DescStringRef DocsUri) {
159    // Avoid MSVC's Compiler Error C2276:
160    // http://msdn.microsoft.com/en-us/library/850cstw1(v=VS.80).aspx
161    addChecker(&CheckerRegistry::initializeManager<T>,
162               &CheckerRegistry::returnTrue<T>, FullName, Desc, DocsUri);
163  }
164
165  /// Makes the checker with the full name \p fullName depends on the checker
166  /// called \p dependency.
167  void addDependency(StringRef fullNameStringRef dependency) {
168    auto CheckerThatNeedsDeps =
169       [&fullName](const CheckerInfo &Chk) { return Chk.FullName == fullName; };
170    auto Dependency =
171      [&dependency](const CheckerInfo &Chk) {
172        return Chk.FullName == dependency;
173      };
174
175    auto CheckerIt = llvm::find_if(Checkers, CheckerThatNeedsDeps);
176     (0) . __assert_fail ("CheckerIt != Checkers.end() && \"Failed to find the checker while attempting to set up it's \" \"dependencies!\"", "/home/seafit/code_projects/clang_source/clang/include/clang/StaticAnalyzer/Frontend/CheckerRegistry.h", 178, __PRETTY_FUNCTION__))" file_link="../../../../../include/assert.h.html#88" macro="true">assert(CheckerIt != Checkers.end() &&
177 (0) . __assert_fail ("CheckerIt != Checkers.end() && \"Failed to find the checker while attempting to set up it's \" \"dependencies!\"", "/home/seafit/code_projects/clang_source/clang/include/clang/StaticAnalyzer/Frontend/CheckerRegistry.h", 178, __PRETTY_FUNCTION__))" file_link="../../../../../include/assert.h.html#88" macro="true">           "Failed to find the checker while attempting to set up it's "
178 (0) . __assert_fail ("CheckerIt != Checkers.end() && \"Failed to find the checker while attempting to set up it's \" \"dependencies!\"", "/home/seafit/code_projects/clang_source/clang/include/clang/StaticAnalyzer/Frontend/CheckerRegistry.h", 178, __PRETTY_FUNCTION__))" file_link="../../../../../include/assert.h.html#88" macro="true">           "dependencies!");
179
180    auto DependencyIt = llvm::find_if(Checkers, Dependency);
181     (0) . __assert_fail ("DependencyIt != Checkers.end() && \"Failed to find the dependency of a checker!\"", "/home/seafit/code_projects/clang_source/clang/include/clang/StaticAnalyzer/Frontend/CheckerRegistry.h", 182, __PRETTY_FUNCTION__))" file_link="../../../../../include/assert.h.html#88" macro="true">assert(DependencyIt != Checkers.end() &&
182 (0) . __assert_fail ("DependencyIt != Checkers.end() && \"Failed to find the dependency of a checker!\"", "/home/seafit/code_projects/clang_source/clang/include/clang/StaticAnalyzer/Frontend/CheckerRegistry.h", 182, __PRETTY_FUNCTION__))" file_link="../../../../../include/assert.h.html#88" macro="true">           "Failed to find the dependency of a checker!");
183
184    CheckerIt->Dependencies.push_back(&*DependencyIt);
185  }
186
187  // FIXME: This *really* should be added to the frontend flag descriptions.
188  /// Initializes a CheckerManager by calling the initialization functions for
189  /// all checkers specified by the given CheckerOptInfo list. The order of this
190  /// list is significant; later options can be used to reverse earlier ones.
191  /// This can be used to exclude certain checkers in an included package.
192  void initializeManager(CheckerManager &mgrconst;
193
194  /// Check if every option corresponds to a specific checker or package.
195  void validateCheckerOptions() const;
196
197  /// Prints the name and description of all checkers in this registry.
198  /// This output is not intended to be machine-parseable.
199  void printHelp(raw_ostream &out, size_t maxNameChars = 30const;
200  void printList(raw_ostream &outconst;
201
202private:
203  /// Collect all enabled checkers. The returned container preserves the order
204  /// of insertion, as dependencies have to be enabled before the checkers that
205  /// depend on them.
206  CheckerInfoSet getEnabledCheckers() const;
207
208  /// Return an iterator range of mutable CheckerInfos \p CmdLineArg applies to.
209  /// For example, it'll return the checkers for the core package, if
210  /// \p CmdLineArg is "core".
211  CheckerInfoListRange getMutableCheckersForCmdLineArg(StringRef CmdLineArg);
212
213  CheckerInfoList Checkers;
214  llvm::StringMap<size_t> Packages;
215
216  DiagnosticsEngine &Diags;
217  AnalyzerOptions &AnOpts;
218  const LangOptions &LangOpts;
219};
220
221// namespace ento
222
223// namespace clang
224
225#endif // LLVM_CLANG_STATICANALYZER_CORE_CHECKERREGISTRY_H
226
clang::ento::CheckerRegistry::CheckerInfo
clang::ento::CheckerRegistry::CheckerInfo::StateFromCmdLine
clang::ento::CheckerRegistry::CheckerInfo::Initialize
clang::ento::CheckerRegistry::CheckerInfo::ShouldRegister
clang::ento::CheckerRegistry::CheckerInfo::FullName
clang::ento::CheckerRegistry::CheckerInfo::Desc
clang::ento::CheckerRegistry::CheckerInfo::DocumentationUri
clang::ento::CheckerRegistry::CheckerInfo::State
clang::ento::CheckerRegistry::CheckerInfo::Dependencies
clang::ento::CheckerRegistry::CheckerInfo::isEnabled
clang::ento::CheckerRegistry::CheckerInfo::isDisabled
clang::ento::CheckerRegistry::initializeManager
clang::ento::CheckerRegistry::returnTrue
clang::ento::CheckerRegistry::addChecker
clang::ento::CheckerRegistry::addChecker
clang::ento::CheckerRegistry::addDependency
clang::ento::CheckerRegistry::initializeManager
clang::ento::CheckerRegistry::validateCheckerOptions
clang::ento::CheckerRegistry::printHelp
clang::ento::CheckerRegistry::printList
clang::ento::CheckerRegistry::getEnabledCheckers
clang::ento::CheckerRegistry::getMutableCheckersForCmdLineArg
clang::ento::CheckerRegistry::Checkers
clang::ento::CheckerRegistry::Packages
clang::ento::CheckerRegistry::Diags
clang::ento::CheckerRegistry::AnOpts
clang::ento::CheckerRegistry::LangOpts