CheckerRegistry.cpp 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528
  1. //===- CheckerRegistry.cpp - Maintains all available checkers -------------===//
  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. #include "clang/StaticAnalyzer/Frontend/CheckerRegistry.h"
  9. #include "clang/Basic/Diagnostic.h"
  10. #include "clang/Basic/LLVM.h"
  11. #include "clang/Driver/DriverDiagnostic.h"
  12. #include "clang/Frontend/FrontendDiagnostic.h"
  13. #include "clang/StaticAnalyzer/Checkers/BuiltinCheckerRegistration.h"
  14. #include "clang/StaticAnalyzer/Core/AnalyzerOptions.h"
  15. #include "clang/StaticAnalyzer/Core/CheckerManager.h"
  16. #include "llvm/ADT/STLExtras.h"
  17. #include "llvm/ADT/StringMap.h"
  18. #include "llvm/ADT/StringRef.h"
  19. #include "llvm/Support/DynamicLibrary.h"
  20. #include "llvm/Support/Path.h"
  21. #include "llvm/Support/raw_ostream.h"
  22. #include <algorithm>
  23. using namespace clang;
  24. using namespace ento;
  25. using namespace checker_registry;
  26. using llvm::sys::DynamicLibrary;
  27. //===----------------------------------------------------------------------===//
  28. // Utilities.
  29. //===----------------------------------------------------------------------===//
  30. static bool isCompatibleAPIVersion(const char *VersionString) {
  31. // If the version string is null, its not an analyzer plugin.
  32. if (!VersionString)
  33. return false;
  34. // For now, none of the static analyzer API is considered stable.
  35. // Versions must match exactly.
  36. return strcmp(VersionString, CLANG_ANALYZER_API_VERSION_STRING) == 0;
  37. }
  38. static constexpr char PackageSeparator = '.';
  39. //===----------------------------------------------------------------------===//
  40. // Methods of CheckerRegistry.
  41. //===----------------------------------------------------------------------===//
  42. CheckerRegistry::CheckerRegistry(
  43. CheckerRegistryData &Data, ArrayRef<std::string> Plugins,
  44. DiagnosticsEngine &Diags, AnalyzerOptions &AnOpts,
  45. ArrayRef<std::function<void(CheckerRegistry &)>> CheckerRegistrationFns)
  46. : Data(Data), Diags(Diags), AnOpts(AnOpts) {
  47. // Register builtin checkers.
  48. #define GET_CHECKERS
  49. #define CHECKER(FULLNAME, CLASS, HELPTEXT, DOC_URI, IS_HIDDEN) \
  50. addChecker(register##CLASS, shouldRegister##CLASS, FULLNAME, HELPTEXT, \
  51. DOC_URI, IS_HIDDEN);
  52. #define GET_PACKAGES
  53. #define PACKAGE(FULLNAME) addPackage(FULLNAME);
  54. #include "clang/StaticAnalyzer/Checkers/Checkers.inc"
  55. #undef CHECKER
  56. #undef GET_CHECKERS
  57. #undef PACKAGE
  58. #undef GET_PACKAGES
  59. // Register checkers from plugins.
  60. for (const std::string &Plugin : Plugins) {
  61. // Get access to the plugin.
  62. std::string ErrorMsg;
  63. DynamicLibrary Lib =
  64. DynamicLibrary::getPermanentLibrary(Plugin.c_str(), &ErrorMsg);
  65. if (!Lib.isValid()) {
  66. Diags.Report(diag::err_fe_unable_to_load_plugin) << Plugin << ErrorMsg;
  67. continue;
  68. }
  69. // See if its compatible with this build of clang.
  70. const char *PluginAPIVersion = static_cast<const char *>(
  71. Lib.getAddressOfSymbol("clang_analyzerAPIVersionString"));
  72. if (!isCompatibleAPIVersion(PluginAPIVersion)) {
  73. Diags.Report(diag::warn_incompatible_analyzer_plugin_api)
  74. << llvm::sys::path::filename(Plugin);
  75. Diags.Report(diag::note_incompatible_analyzer_plugin_api)
  76. << CLANG_ANALYZER_API_VERSION_STRING << PluginAPIVersion;
  77. continue;
  78. }
  79. using RegisterPluginCheckerFn = void (*)(CheckerRegistry &);
  80. // Register its checkers.
  81. RegisterPluginCheckerFn RegisterPluginCheckers =
  82. reinterpret_cast<RegisterPluginCheckerFn>(
  83. Lib.getAddressOfSymbol("clang_registerCheckers"));
  84. if (RegisterPluginCheckers)
  85. RegisterPluginCheckers(*this);
  86. }
  87. // Register statically linked checkers, that aren't generated from the tblgen
  88. // file, but rather passed their registry function as a parameter in
  89. // checkerRegistrationFns.
  90. for (const auto &Fn : CheckerRegistrationFns)
  91. Fn(*this);
  92. // Sort checkers for efficient collection.
  93. // FIXME: Alphabetical sort puts 'experimental' in the middle.
  94. // Would it be better to name it '~experimental' or something else
  95. // that's ASCIIbetically last?
  96. llvm::sort(Data.Packages, checker_registry::PackageNameLT{});
  97. llvm::sort(Data.Checkers, checker_registry::CheckerNameLT{});
  98. #define GET_CHECKER_DEPENDENCIES
  99. #define CHECKER_DEPENDENCY(FULLNAME, DEPENDENCY) \
  100. addDependency(FULLNAME, DEPENDENCY);
  101. #define GET_CHECKER_WEAK_DEPENDENCIES
  102. #define CHECKER_WEAK_DEPENDENCY(FULLNAME, DEPENDENCY) \
  103. addWeakDependency(FULLNAME, DEPENDENCY);
  104. #define GET_CHECKER_OPTIONS
  105. #define CHECKER_OPTION(TYPE, FULLNAME, CMDFLAG, DESC, DEFAULT_VAL, \
  106. DEVELOPMENT_STATUS, IS_HIDDEN) \
  107. addCheckerOption(TYPE, FULLNAME, CMDFLAG, DEFAULT_VAL, DESC, \
  108. DEVELOPMENT_STATUS, IS_HIDDEN);
  109. #define GET_PACKAGE_OPTIONS
  110. #define PACKAGE_OPTION(TYPE, FULLNAME, CMDFLAG, DESC, DEFAULT_VAL, \
  111. DEVELOPMENT_STATUS, IS_HIDDEN) \
  112. addPackageOption(TYPE, FULLNAME, CMDFLAG, DEFAULT_VAL, DESC, \
  113. DEVELOPMENT_STATUS, IS_HIDDEN);
  114. #include "clang/StaticAnalyzer/Checkers/Checkers.inc"
  115. #undef CHECKER_DEPENDENCY
  116. #undef GET_CHECKER_DEPENDENCIES
  117. #undef CHECKER_WEAK_DEPENDENCY
  118. #undef GET_CHECKER_WEAK_DEPENDENCIES
  119. #undef CHECKER_OPTION
  120. #undef GET_CHECKER_OPTIONS
  121. #undef PACKAGE_OPTION
  122. #undef GET_PACKAGE_OPTIONS
  123. resolveDependencies<true>();
  124. resolveDependencies<false>();
  125. #ifndef NDEBUG
  126. for (auto &DepPair : Data.Dependencies) {
  127. for (auto &WeakDepPair : Data.WeakDependencies) {
  128. // Some assertions to enforce that strong dependencies are relations in
  129. // between purely modeling checkers, and weak dependencies are about
  130. // diagnostics.
  131. assert(WeakDepPair != DepPair &&
  132. "A checker cannot strong and weak depend on the same checker!");
  133. assert(WeakDepPair.first != DepPair.second &&
  134. "A strong dependency mustn't have weak dependencies!");
  135. assert(WeakDepPair.second != DepPair.second &&
  136. "A strong dependency mustn't be a weak dependency as well!");
  137. }
  138. }
  139. #endif
  140. resolveCheckerAndPackageOptions();
  141. // Parse '-analyzer-checker' and '-analyzer-disable-checker' options from the
  142. // command line.
  143. for (const std::pair<std::string, bool> &Opt : AnOpts.CheckersAndPackages) {
  144. CheckerInfoListRange CheckerForCmdLineArg =
  145. Data.getMutableCheckersForCmdLineArg(Opt.first);
  146. if (CheckerForCmdLineArg.begin() == CheckerForCmdLineArg.end()) {
  147. Diags.Report(diag::err_unknown_analyzer_checker_or_package) << Opt.first;
  148. Diags.Report(diag::note_suggest_disabling_all_checkers);
  149. }
  150. for (CheckerInfo &checker : CheckerForCmdLineArg) {
  151. checker.State = Opt.second ? StateFromCmdLine::State_Enabled
  152. : StateFromCmdLine::State_Disabled;
  153. }
  154. }
  155. validateCheckerOptions();
  156. }
  157. //===----------------------------------------------------------------------===//
  158. // Dependency resolving.
  159. //===----------------------------------------------------------------------===//
  160. template <typename IsEnabledFn>
  161. static bool collectStrongDependencies(const ConstCheckerInfoList &Deps,
  162. const CheckerManager &Mgr,
  163. CheckerInfoSet &Ret,
  164. IsEnabledFn IsEnabled);
  165. /// Collects weak dependencies in \p enabledData.Checkers.
  166. template <typename IsEnabledFn>
  167. static void collectWeakDependencies(const ConstCheckerInfoList &Deps,
  168. const CheckerManager &Mgr,
  169. CheckerInfoSet &Ret, IsEnabledFn IsEnabled);
  170. void CheckerRegistry::initializeRegistry(const CheckerManager &Mgr) {
  171. // First, we calculate the list of enabled checkers as specified by the
  172. // invocation. Weak dependencies will not enable their unspecified strong
  173. // depenencies, but its only after resolving strong dependencies for all
  174. // checkers when we know whether they will be enabled.
  175. CheckerInfoSet Tmp;
  176. auto IsEnabledFromCmdLine = [&](const CheckerInfo *Checker) {
  177. return !Checker->isDisabled(Mgr);
  178. };
  179. for (const CheckerInfo &Checker : Data.Checkers) {
  180. if (!Checker.isEnabled(Mgr))
  181. continue;
  182. CheckerInfoSet Deps;
  183. if (!collectStrongDependencies(Checker.Dependencies, Mgr, Deps,
  184. IsEnabledFromCmdLine)) {
  185. // If we failed to enable any of the dependencies, don't enable this
  186. // checker.
  187. continue;
  188. }
  189. Tmp.insert(Deps.begin(), Deps.end());
  190. // Enable the checker.
  191. Tmp.insert(&Checker);
  192. }
  193. // Calculate enabled checkers with the correct registration order. As this is
  194. // done recursively, its arguably cheaper, but for sure less error prone to
  195. // recalculate from scratch.
  196. auto IsEnabled = [&](const CheckerInfo *Checker) {
  197. return llvm::is_contained(Tmp, Checker);
  198. };
  199. for (const CheckerInfo &Checker : Data.Checkers) {
  200. if (!Checker.isEnabled(Mgr))
  201. continue;
  202. CheckerInfoSet Deps;
  203. collectWeakDependencies(Checker.WeakDependencies, Mgr, Deps, IsEnabled);
  204. if (!collectStrongDependencies(Checker.Dependencies, Mgr, Deps,
  205. IsEnabledFromCmdLine)) {
  206. // If we failed to enable any of the dependencies, don't enable this
  207. // checker.
  208. continue;
  209. }
  210. // Note that set_union also preserves the order of insertion.
  211. Data.EnabledCheckers.set_union(Deps);
  212. Data.EnabledCheckers.insert(&Checker);
  213. }
  214. }
  215. template <typename IsEnabledFn>
  216. static bool collectStrongDependencies(const ConstCheckerInfoList &Deps,
  217. const CheckerManager &Mgr,
  218. CheckerInfoSet &Ret,
  219. IsEnabledFn IsEnabled) {
  220. for (const CheckerInfo *Dependency : Deps) {
  221. if (!IsEnabled(Dependency))
  222. return false;
  223. // Collect dependencies recursively.
  224. if (!collectStrongDependencies(Dependency->Dependencies, Mgr, Ret,
  225. IsEnabled))
  226. return false;
  227. Ret.insert(Dependency);
  228. }
  229. return true;
  230. }
  231. template <typename IsEnabledFn>
  232. static void collectWeakDependencies(const ConstCheckerInfoList &WeakDeps,
  233. const CheckerManager &Mgr,
  234. CheckerInfoSet &Ret,
  235. IsEnabledFn IsEnabled) {
  236. for (const CheckerInfo *Dependency : WeakDeps) {
  237. // Don't enable this checker if strong dependencies are unsatisfied, but
  238. // assume that weak dependencies are transitive.
  239. collectWeakDependencies(Dependency->WeakDependencies, Mgr, Ret, IsEnabled);
  240. if (IsEnabled(Dependency) &&
  241. collectStrongDependencies(Dependency->Dependencies, Mgr, Ret,
  242. IsEnabled))
  243. Ret.insert(Dependency);
  244. }
  245. }
  246. template <bool IsWeak> void CheckerRegistry::resolveDependencies() {
  247. for (const std::pair<StringRef, StringRef> &Entry :
  248. (IsWeak ? Data.WeakDependencies : Data.Dependencies)) {
  249. auto CheckerIt = binaryFind(Data.Checkers, Entry.first);
  250. assert(CheckerIt != Data.Checkers.end() &&
  251. CheckerIt->FullName == Entry.first &&
  252. "Failed to find the checker while attempting to set up its "
  253. "dependencies!");
  254. auto DependencyIt = binaryFind(Data.Checkers, Entry.second);
  255. assert(DependencyIt != Data.Checkers.end() &&
  256. DependencyIt->FullName == Entry.second &&
  257. "Failed to find the dependency of a checker!");
  258. // We do allow diagnostics from unit test/example dependency checkers.
  259. assert((DependencyIt->FullName.startswith("test") ||
  260. DependencyIt->FullName.startswith("example") || IsWeak ||
  261. DependencyIt->IsHidden) &&
  262. "Strong dependencies are modeling checkers, and as such "
  263. "non-user facing! Mark them hidden in Checkers.td!");
  264. if (IsWeak)
  265. CheckerIt->WeakDependencies.emplace_back(&*DependencyIt);
  266. else
  267. CheckerIt->Dependencies.emplace_back(&*DependencyIt);
  268. }
  269. }
  270. void CheckerRegistry::addDependency(StringRef FullName, StringRef Dependency) {
  271. Data.Dependencies.emplace_back(FullName, Dependency);
  272. }
  273. void CheckerRegistry::addWeakDependency(StringRef FullName,
  274. StringRef Dependency) {
  275. Data.WeakDependencies.emplace_back(FullName, Dependency);
  276. }
  277. //===----------------------------------------------------------------------===//
  278. // Checker option resolving and validating.
  279. //===----------------------------------------------------------------------===//
  280. /// Insert the checker/package option to AnalyzerOptions' config table, and
  281. /// validate it, if the user supplied it on the command line.
  282. static void insertAndValidate(StringRef FullName, const CmdLineOption &Option,
  283. AnalyzerOptions &AnOpts,
  284. DiagnosticsEngine &Diags) {
  285. std::string FullOption = (FullName + ":" + Option.OptionName).str();
  286. auto It =
  287. AnOpts.Config.insert({FullOption, std::string(Option.DefaultValStr)});
  288. // Insertation was successful -- CmdLineOption's constructor will validate
  289. // whether values received from plugins or TableGen files are correct.
  290. if (It.second)
  291. return;
  292. // Insertion failed, the user supplied this package/checker option on the
  293. // command line. If the supplied value is invalid, we'll restore the option
  294. // to it's default value, and if we're in non-compatibility mode, we'll also
  295. // emit an error.
  296. StringRef SuppliedValue = It.first->getValue();
  297. if (Option.OptionType == "bool") {
  298. if (SuppliedValue != "true" && SuppliedValue != "false") {
  299. if (AnOpts.ShouldEmitErrorsOnInvalidConfigValue) {
  300. Diags.Report(diag::err_analyzer_checker_option_invalid_input)
  301. << FullOption << "a boolean value";
  302. }
  303. It.first->setValue(std::string(Option.DefaultValStr));
  304. }
  305. return;
  306. }
  307. if (Option.OptionType == "int") {
  308. int Tmp;
  309. bool HasFailed = SuppliedValue.getAsInteger(0, Tmp);
  310. if (HasFailed) {
  311. if (AnOpts.ShouldEmitErrorsOnInvalidConfigValue) {
  312. Diags.Report(diag::err_analyzer_checker_option_invalid_input)
  313. << FullOption << "an integer value";
  314. }
  315. It.first->setValue(std::string(Option.DefaultValStr));
  316. }
  317. return;
  318. }
  319. }
  320. template <class T>
  321. static void insertOptionToCollection(StringRef FullName, T &Collection,
  322. const CmdLineOption &Option,
  323. AnalyzerOptions &AnOpts,
  324. DiagnosticsEngine &Diags) {
  325. auto It = binaryFind(Collection, FullName);
  326. assert(It != Collection.end() &&
  327. "Failed to find the checker while attempting to add a command line "
  328. "option to it!");
  329. insertAndValidate(FullName, Option, AnOpts, Diags);
  330. It->CmdLineOptions.emplace_back(Option);
  331. }
  332. void CheckerRegistry::resolveCheckerAndPackageOptions() {
  333. for (const std::pair<StringRef, CmdLineOption> &CheckerOptEntry :
  334. Data.CheckerOptions) {
  335. insertOptionToCollection(CheckerOptEntry.first, Data.Checkers,
  336. CheckerOptEntry.second, AnOpts, Diags);
  337. }
  338. for (const std::pair<StringRef, CmdLineOption> &PackageOptEntry :
  339. Data.PackageOptions) {
  340. insertOptionToCollection(PackageOptEntry.first, Data.Packages,
  341. PackageOptEntry.second, AnOpts, Diags);
  342. }
  343. }
  344. void CheckerRegistry::addPackage(StringRef FullName) {
  345. Data.Packages.emplace_back(PackageInfo(FullName));
  346. }
  347. void CheckerRegistry::addPackageOption(StringRef OptionType,
  348. StringRef PackageFullName,
  349. StringRef OptionName,
  350. StringRef DefaultValStr,
  351. StringRef Description,
  352. StringRef DevelopmentStatus,
  353. bool IsHidden) {
  354. Data.PackageOptions.emplace_back(
  355. PackageFullName, CmdLineOption{OptionType, OptionName, DefaultValStr,
  356. Description, DevelopmentStatus, IsHidden});
  357. }
  358. void CheckerRegistry::addChecker(RegisterCheckerFn Rfn,
  359. ShouldRegisterFunction Sfn, StringRef Name,
  360. StringRef Desc, StringRef DocsUri,
  361. bool IsHidden) {
  362. Data.Checkers.emplace_back(Rfn, Sfn, Name, Desc, DocsUri, IsHidden);
  363. // Record the presence of the checker in its packages.
  364. StringRef PackageName, LeafName;
  365. std::tie(PackageName, LeafName) = Name.rsplit(PackageSeparator);
  366. while (!LeafName.empty()) {
  367. Data.PackageSizes[PackageName] += 1;
  368. std::tie(PackageName, LeafName) = PackageName.rsplit(PackageSeparator);
  369. }
  370. }
  371. void CheckerRegistry::addCheckerOption(StringRef OptionType,
  372. StringRef CheckerFullName,
  373. StringRef OptionName,
  374. StringRef DefaultValStr,
  375. StringRef Description,
  376. StringRef DevelopmentStatus,
  377. bool IsHidden) {
  378. Data.CheckerOptions.emplace_back(
  379. CheckerFullName, CmdLineOption{OptionType, OptionName, DefaultValStr,
  380. Description, DevelopmentStatus, IsHidden});
  381. }
  382. void CheckerRegistry::initializeManager(CheckerManager &CheckerMgr) const {
  383. // Initialize the CheckerManager with all enabled checkers.
  384. for (const auto *Checker : Data.EnabledCheckers) {
  385. CheckerMgr.setCurrentCheckerName(CheckerNameRef(Checker->FullName));
  386. Checker->Initialize(CheckerMgr);
  387. }
  388. }
  389. static void isOptionContainedIn(const CmdLineOptionList &OptionList,
  390. StringRef SuppliedChecker,
  391. StringRef SuppliedOption,
  392. const AnalyzerOptions &AnOpts,
  393. DiagnosticsEngine &Diags) {
  394. if (!AnOpts.ShouldEmitErrorsOnInvalidConfigValue)
  395. return;
  396. auto SameOptName = [SuppliedOption](const CmdLineOption &Opt) {
  397. return Opt.OptionName == SuppliedOption;
  398. };
  399. if (llvm::none_of(OptionList, SameOptName)) {
  400. Diags.Report(diag::err_analyzer_checker_option_unknown)
  401. << SuppliedChecker << SuppliedOption;
  402. return;
  403. }
  404. }
  405. void CheckerRegistry::validateCheckerOptions() const {
  406. for (const auto &Config : AnOpts.Config) {
  407. StringRef SuppliedCheckerOrPackage;
  408. StringRef SuppliedOption;
  409. std::tie(SuppliedCheckerOrPackage, SuppliedOption) =
  410. Config.getKey().split(':');
  411. if (SuppliedOption.empty())
  412. continue;
  413. // AnalyzerOptions' config table contains the user input, so an entry could
  414. // look like this:
  415. //
  416. // cor:NoFalsePositives=true
  417. //
  418. // Since lower_bound would look for the first element *not less* than "cor",
  419. // it would return with an iterator to the first checker in the core, so we
  420. // we really have to use find here, which uses operator==.
  421. auto CheckerIt =
  422. llvm::find(Data.Checkers, CheckerInfo(SuppliedCheckerOrPackage));
  423. if (CheckerIt != Data.Checkers.end()) {
  424. isOptionContainedIn(CheckerIt->CmdLineOptions, SuppliedCheckerOrPackage,
  425. SuppliedOption, AnOpts, Diags);
  426. continue;
  427. }
  428. const auto *PackageIt =
  429. llvm::find(Data.Packages, PackageInfo(SuppliedCheckerOrPackage));
  430. if (PackageIt != Data.Packages.end()) {
  431. isOptionContainedIn(PackageIt->CmdLineOptions, SuppliedCheckerOrPackage,
  432. SuppliedOption, AnOpts, Diags);
  433. continue;
  434. }
  435. Diags.Report(diag::err_unknown_analyzer_checker_or_package)
  436. << SuppliedCheckerOrPackage;
  437. }
  438. }