CheckerRegistry.cpp 20 KB

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