1 /* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
2 file Copyright.txt or https://cmake.org/licensing for details. */
3 #include "cmFindPackageCommand.h"
15 #include <cm/optional>
16 #include <cmext/string_view>
18 #include "cmsys/Directory.hxx"
19 #include "cmsys/FStream.hxx"
20 #include "cmsys/Glob.hxx"
21 #include "cmsys/RegularExpression.hxx"
22 #include "cmsys/String.h"
24 #include "cmAlgorithms.h"
25 #include "cmDependencyProvider.h"
26 #include "cmListFileCache.h"
27 #include "cmMakefile.h"
28 #include "cmMessageType.h"
29 #include "cmPolicies.h"
31 #include "cmSearchPath.h"
33 #include "cmStateTypes.h"
34 #include "cmStringAlgorithms.h"
35 #include "cmSystemTools.h"
37 #include "cmVersion.h"
38 #include "cmWindowsRegistry.h"
40 #if defined(__HAIKU__)
41 # include <FindDirectory.h>
42 # include <StorageDefs.h>
45 #if defined(_WIN32) && !defined(__CYGWIN__)
47 // http://msdn.microsoft.com/en-us/library/aa384253%28v=vs.85%29.aspx
48 # if !defined(KEY_WOW64_32KEY)
49 # define KEY_WOW64_32KEY 0x0200
51 # if !defined(KEY_WOW64_64KEY)
52 # define KEY_WOW64_64KEY 0x0100
56 class cmExecutionStatus;
60 template <template <typename> class Op>
63 bool operator()(const std::string& lhs, const std::string& rhs) const
65 return Op<int>()(cmSystemTools::strverscmp(lhs, rhs), 0);
69 std::size_t collectPathsForDebug(std::string& buffer,
70 cmSearchPath const& searchPath,
71 std::size_t const startIndex = 0)
73 const auto& paths = searchPath.GetPaths();
78 for (auto i = startIndex; i < paths.size(); i++) {
79 buffer += " " + paths[i].Path + "\n";
84 #if !(defined(_WIN32) && !defined(__CYGWIN__))
85 class cmFindPackageCommandHoldFile
90 cmFindPackageCommandHoldFile(const char* const f)
94 ~cmFindPackageCommandHoldFile()
97 cmSystemTools::RemoveFile(this->File);
100 cmFindPackageCommandHoldFile(const cmFindPackageCommandHoldFile&) = delete;
101 cmFindPackageCommandHoldFile& operator=(
102 const cmFindPackageCommandHoldFile&) = delete;
103 void Release() { this->File = nullptr; }
107 bool isDirentryToIgnore(const char* const fname)
109 assert(fname != nullptr);
110 assert(fname[0] != 0);
111 return fname[0] == '.' &&
112 (fname[1] == 0 || (fname[1] == '.' && fname[2] == 0));
115 class cmAppendPathSegmentGenerator
118 cmAppendPathSegmentGenerator(cm::string_view dirName)
123 std::string GetNextCandidate(const std::string& parent)
125 if (this->NeedReset) {
128 this->NeedReset = true;
129 return cmStrCat(parent, '/', this->DirName);
132 void Reset() { this->NeedReset = false; }
135 const cm::string_view DirName;
136 bool NeedReset = false;
139 class cmEnumPathSegmentsGenerator
142 cmEnumPathSegmentsGenerator(const std::vector<cm::string_view>& init)
144 , Current{ this->Names.get().cbegin() }
148 std::string GetNextCandidate(const std::string& parent)
150 if (this->Current != this->Names.get().cend()) {
151 return cmStrCat(parent, '/', *this->Current++);
156 void Reset() { this->Current = this->Names.get().cbegin(); }
159 std::reference_wrapper<const std::vector<cm::string_view>> Names;
160 std::vector<cm::string_view>::const_iterator Current;
163 class cmCaseInsensitiveDirectoryListGenerator
166 cmCaseInsensitiveDirectoryListGenerator(cm::string_view name)
172 std::string GetNextCandidate(const std::string& parent)
175 this->CurrentIdx = 0ul;
177 if (!this->DirectoryLister.Load(parent)) {
182 while (this->CurrentIdx < this->DirectoryLister.GetNumberOfFiles()) {
183 const char* const fname =
184 this->DirectoryLister.GetFile(this->CurrentIdx++);
185 if (isDirentryToIgnore(fname)) {
188 if (cmsysString_strcasecmp(fname, this->DirName.data()) == 0) {
189 auto candidate = cmStrCat(parent, '/', fname);
190 if (cmSystemTools::FileIsDirectory(candidate)) {
198 void Reset() { this->Loaded = false; }
201 cmsys::Directory DirectoryLister;
202 const cm::string_view DirName;
203 unsigned long CurrentIdx = 0ul;
207 class cmDirectoryListGenerator
210 cmDirectoryListGenerator(std::vector<std::string> const& names)
213 , Current{ this->Matches.cbegin() }
216 virtual ~cmDirectoryListGenerator() = default;
218 std::string GetNextCandidate(const std::string& parent)
220 // Construct a list of matches if not yet
221 if (this->Matches.empty()) {
222 cmsys::Directory directoryLister;
223 // ALERT `Directory::Load()` keeps only names
224 // internally and LOST entry type from `dirent`.
225 // So, `Directory::FileIsDirectory` gonna use
226 // `SystemTools::FileIsDirectory()` and waste a syscall.
227 // TODO Need to enhance the `Directory` class.
228 directoryLister.Load(parent);
230 // ATTENTION Is it guaranteed that first two entries are
232 // TODO If so, just start with index 2 and drop the
233 // `isDirentryToIgnore(i)` condition to check.
234 for (auto i = 0ul; i < directoryLister.GetNumberOfFiles(); ++i) {
235 const char* const fname = directoryLister.GetFile(i);
236 if (isDirentryToIgnore(fname)) {
240 for (const auto& n : this->Names.get()) {
241 // NOTE Customization point for `cmMacProjectDirectoryListGenerator`
242 const auto name = this->TransformNameBeforeCmp(n);
243 // Skip entries that don't match and non-directories.
244 // ATTENTION BTW, original code also didn't check if it's a symlink
247 (cmsysString_strncasecmp(fname, name.c_str(), name.length()) == 0);
248 if (equal && directoryLister.FileIsDirectory(i)) {
249 this->Matches.emplace_back(fname);
253 // NOTE Customization point for `cmProjectDirectoryListGenerator`
254 this->OnMatchesLoaded();
256 this->Current = this->Matches.cbegin();
259 if (this->Current != this->Matches.cend()) {
260 auto candidate = cmStrCat(parent, '/', *this->Current++);
269 this->Matches.clear();
270 this->Current = this->Matches.cbegin();
274 virtual void OnMatchesLoaded() {}
275 virtual std::string TransformNameBeforeCmp(std::string same) { return same; }
277 std::reference_wrapper<const std::vector<std::string>> Names;
278 std::vector<std::string> Matches;
279 std::vector<std::string>::const_iterator Current;
282 class cmProjectDirectoryListGenerator : public cmDirectoryListGenerator
285 cmProjectDirectoryListGenerator(std::vector<std::string> const& names,
286 cmFindPackageCommand::SortOrderType so,
287 cmFindPackageCommand::SortDirectionType sd)
288 : cmDirectoryListGenerator{ names }
290 , SortDirection{ sd }
295 void OnMatchesLoaded() override
297 // check if there is a specific sorting order to perform
298 if (this->SortOrder != cmFindPackageCommand::None) {
299 cmFindPackageCommand::Sort(this->Matches.begin(), this->Matches.end(),
300 this->SortOrder, this->SortDirection);
306 const cmFindPackageCommand::SortOrderType SortOrder;
307 const cmFindPackageCommand::SortDirectionType SortDirection;
310 class cmMacProjectDirectoryListGenerator : public cmDirectoryListGenerator
313 cmMacProjectDirectoryListGenerator(const std::vector<std::string>& names,
315 : cmDirectoryListGenerator{ names }
321 std::string TransformNameBeforeCmp(std::string name) override
323 return cmStrCat(name, this->Extension);
327 const cm::string_view Extension;
330 class cmFileListGeneratorGlob
333 cmFileListGeneratorGlob(cm::string_view pattern)
340 std::string GetNextCandidate(const std::string& parent)
342 if (this->Files.empty()) {
343 // Glob the set of matching files.
344 std::string expr = cmStrCat(parent, this->Pattern);
346 if (!g.FindFiles(expr)) {
349 this->Files = g.GetFiles();
350 this->Current = this->Files.cbegin();
353 // Skip non-directories
354 for (; this->Current != this->Files.cend() &&
355 !cmSystemTools::FileIsDirectory(*this->Current);
359 return (this->Current != this->Files.cend()) ? *this->Current++
366 this->Current = this->Files.cbegin();
370 cm::string_view Pattern;
371 std::vector<std::string> Files;
372 std::vector<std::string>::const_iterator Current;
376 # define CM_LCC_DIAG_SUPPRESS_1222
377 # pragma diag_suppress 1222 // invalid error number (3288, but works anyway)
378 # define CM_LCC_DIAG_SUPPRESS_3288
379 # pragma diag_suppress 3288 // parameter was declared but never referenced
382 void ResetGenerator()
386 template <typename Generator>
387 void ResetGenerator(Generator&& generator)
389 std::forward<Generator&&>(generator).Reset();
392 template <typename Generator, typename... Generators>
393 void ResetGenerator(Generator&& generator, Generators&&... generators)
395 ResetGenerator(std::forward<Generator&&>(generator));
396 ResetGenerator(std::forward<Generators&&>(generators)...);
399 template <typename CallbackFn>
400 bool TryGeneratedPaths(CallbackFn&& filesCollector,
401 const std::string& fullPath)
403 assert(!fullPath.empty() && fullPath.back() != '/');
404 return std::forward<CallbackFn&&>(filesCollector)(fullPath + '/');
407 template <typename CallbackFn, typename Generator, typename... Rest>
408 bool TryGeneratedPaths(CallbackFn&& filesCollector,
409 const std::string& startPath, Generator&& gen,
412 ResetGenerator(std::forward<Generator&&>(gen));
413 for (auto path = gen.GetNextCandidate(startPath); !path.empty();
414 path = gen.GetNextCandidate(startPath)) {
415 ResetGenerator(std::forward<Rest&&>(tail)...);
416 if (TryGeneratedPaths(std::forward<CallbackFn&&>(filesCollector), path,
417 std::forward<Rest&&>(tail)...)) {
424 #ifdef CM_LCC_DIAG_SUPPRESS_3288
425 # undef CM_LCC_DIAG_SUPPRESS_3288
426 # pragma diag_default 3288
429 #ifdef CM_LCC_DIAG_SUPPRESS_1222
430 # undef CM_LCC_DIAG_SUPPRESS_1222
431 # pragma diag_default 1222
434 // Parse the version number and store the results that were
435 // successfully parsed.
436 int parseVersion(const std::string& version, unsigned int& major,
437 unsigned int& minor, unsigned int& patch, unsigned int& tweak)
439 return std::sscanf(version.c_str(), "%u.%u.%u.%u", &major, &minor, &patch,
443 } // anonymous namespace
445 cmFindPackageCommand::PathLabel
446 cmFindPackageCommand::PathLabel::PackageRedirect("PACKAGE_REDIRECT");
447 cmFindPackageCommand::PathLabel cmFindPackageCommand::PathLabel::UserRegistry(
449 cmFindPackageCommand::PathLabel cmFindPackageCommand::PathLabel::Builds(
451 cmFindPackageCommand::PathLabel
452 cmFindPackageCommand::PathLabel::SystemRegistry("SYSTEM_PACKAGE_REGISTRY");
454 const cm::string_view cmFindPackageCommand::VERSION_ENDPOINT_INCLUDED(
456 const cm::string_view cmFindPackageCommand::VERSION_ENDPOINT_EXCLUDED(
459 void cmFindPackageCommand::Sort(std::vector<std::string>::iterator begin,
460 std::vector<std::string>::iterator end,
461 SortOrderType const order,
462 SortDirectionType const dir)
464 if (order == Name_order) {
466 std::sort(begin, end, std::greater<std::string>());
468 std::sort(begin, end);
470 } else if (order == Natural) {
471 // natural order uses letters and numbers (contiguous numbers digit are
472 // compared such that e.g. 000 00 < 01 < 010 < 09 < 0 < 1 < 9 < 10
474 std::sort(begin, end, StrverscmpOp<std::greater>());
476 std::sort(begin, end, StrverscmpOp<std::less>());
482 cmFindPackageCommand::cmFindPackageCommand(cmExecutionStatus& status)
483 : cmFindCommon(status)
484 , VersionRangeMin(VERSION_ENDPOINT_INCLUDED)
485 , VersionRangeMax(VERSION_ENDPOINT_INCLUDED)
487 this->CMakePathName = "PACKAGE";
488 this->DebugMode = false;
489 this->AppendSearchPathGroups();
491 this->DeprecatedFindModules["Qt"] = cmPolicies::CMP0084;
494 void cmFindPackageCommand::AppendSearchPathGroups()
496 // Update the All group with new paths. Note that package redirection must
497 // take precedence over everything else, so it has to be first in the array.
498 std::vector<cmFindCommon::PathLabel>* const labels =
499 &this->PathGroupLabelMap[PathGroup::All];
500 labels->insert(labels->begin(), PathLabel::PackageRedirect);
502 std::find(labels->begin(), labels->end(), PathLabel::CMakeSystem),
503 PathLabel::UserRegistry);
505 std::find(labels->begin(), labels->end(), PathLabel::CMakeSystem),
507 labels->insert(std::find(labels->begin(), labels->end(), PathLabel::Guess),
508 PathLabel::SystemRegistry);
510 // Create the new path objects
511 this->LabeledPaths.insert(
512 std::make_pair(PathLabel::PackageRedirect, cmSearchPath(this)));
513 this->LabeledPaths.insert(
514 std::make_pair(PathLabel::UserRegistry, cmSearchPath(this)));
515 this->LabeledPaths.insert(
516 std::make_pair(PathLabel::Builds, cmSearchPath(this)));
517 this->LabeledPaths.insert(
518 std::make_pair(PathLabel::SystemRegistry, cmSearchPath(this)));
521 bool cmFindPackageCommand::InitialPass(std::vector<std::string> const& args)
524 this->SetError("called with incorrect number of arguments");
528 // Lookup required version of CMake.
529 if (cmValue const rv =
530 this->Makefile->GetDefinition("CMAKE_MINIMUM_REQUIRED_VERSION")) {
531 unsigned int v[3] = { 0, 0, 0 };
532 std::sscanf(rv->c_str(), "%u.%u.%u", &v[0], &v[1], &v[2]);
533 this->RequiredCMakeVersion = CMake_VERSION_ENCODE(v[0], v[1], v[2]);
536 // Lookup target architecture, if any.
537 if (cmValue const arch =
538 this->Makefile->GetDefinition("CMAKE_LIBRARY_ARCHITECTURE")) {
539 this->LibraryArchitecture = *arch;
542 // Lookup whether lib32 paths should be used.
543 if (this->Makefile->PlatformIs32Bit() &&
544 this->Makefile->GetState()->GetGlobalPropertyAsBool(
545 "FIND_LIBRARY_USE_LIB32_PATHS")) {
546 this->UseLib32Paths = true;
549 // Lookup whether lib64 paths should be used.
550 if (this->Makefile->PlatformIs64Bit() &&
551 this->Makefile->GetState()->GetGlobalPropertyAsBool(
552 "FIND_LIBRARY_USE_LIB64_PATHS")) {
553 this->UseLib64Paths = true;
556 // Lookup whether libx32 paths should be used.
557 if (this->Makefile->PlatformIsx32() &&
558 this->Makefile->GetState()->GetGlobalPropertyAsBool(
559 "FIND_LIBRARY_USE_LIBX32_PATHS")) {
560 this->UseLibx32Paths = true;
563 // Check if User Package Registry should be disabled
564 // The `CMAKE_FIND_USE_PACKAGE_REGISTRY` has
565 // priority over the deprecated CMAKE_FIND_PACKAGE_NO_PACKAGE_REGISTRY
566 if (cmValue const def =
567 this->Makefile->GetDefinition("CMAKE_FIND_USE_PACKAGE_REGISTRY")) {
568 this->NoUserRegistry = !cmIsOn(*def);
569 } else if (this->Makefile->IsOn("CMAKE_FIND_PACKAGE_NO_PACKAGE_REGISTRY")) {
570 this->NoUserRegistry = true;
573 // Check if System Package Registry should be disabled
574 // The `CMAKE_FIND_USE_SYSTEM_PACKAGE_REGISTRY` has
575 // priority over the deprecated CMAKE_FIND_PACKAGE_NO_SYSTEM_PACKAGE_REGISTRY
576 if (cmValue const def = this->Makefile->GetDefinition(
577 "CMAKE_FIND_USE_SYSTEM_PACKAGE_REGISTRY")) {
578 this->NoSystemRegistry = !cmIsOn(*def);
579 } else if (this->Makefile->IsOn(
580 "CMAKE_FIND_PACKAGE_NO_SYSTEM_PACKAGE_REGISTRY")) {
581 this->NoSystemRegistry = true;
584 // Check whether we should resolve symlinks when finding packages
585 if (this->Makefile->IsOn("CMAKE_FIND_PACKAGE_RESOLVE_SYMLINKS")) {
586 this->UseRealPath = true;
589 // Check if Sorting should be enabled
590 if (cmValue const so =
591 this->Makefile->GetDefinition("CMAKE_FIND_PACKAGE_SORT_ORDER")) {
594 this->SortOrder = Name_order;
595 } else if (*so == "NATURAL") {
596 this->SortOrder = Natural;
598 this->SortOrder = None;
601 if (cmValue const sd =
602 this->Makefile->GetDefinition("CMAKE_FIND_PACKAGE_SORT_DIRECTION")) {
603 this->SortDirection = (*sd == "ASC") ? Asc : Dec;
606 // Find what search path locations have been enabled/disable
607 this->SelectDefaultSearchModes();
609 // Find the current root path mode.
610 this->SelectDefaultRootPathMode();
612 // Find the current bundle/framework search policy.
613 this->SelectDefaultMacMode();
616 this->Name = args[0];
617 std::string components;
618 const char* components_sep = "";
619 std::set<std::string> requiredComponents;
620 std::set<std::string> optionalComponents;
621 std::vector<std::pair<std::string, const char*>> componentVarDefs;
622 bool bypassProvider = false;
624 // Always search directly in a generated path.
625 this->SearchPathSuffixes.emplace_back();
627 // Process debug mode
628 cmMakefile::DebugFindPkgRAII debugFindPkgRAII(this->Makefile, this->Name);
629 this->DebugMode = this->ComputeIfDebugModeWanted();
631 // Parse the arguments.
636 DoingOptionalComponents,
643 Doing doing = DoingNone;
644 cmsys::RegularExpression versionRegex(
645 R"V(^([0-9]+(\.[0-9]+)*)(\.\.\.(<?)([0-9]+(\.[0-9]+)*))?$)V");
646 bool haveVersion = false;
647 std::vector<std::size_t> configArgs;
648 std::vector<std::size_t> moduleArgs;
649 for (std::size_t i = 1u; i < args.size(); ++i) {
650 if (args[i] == "QUIET") {
653 } else if (args[i] == "BYPASS_PROVIDER") {
654 bypassProvider = true;
656 } else if (args[i] == "EXACT") {
657 this->VersionExact = true;
659 } else if (args[i] == "GLOBAL") {
660 this->GlobalScope = true;
662 } else if (args[i] == "MODULE") {
663 moduleArgs.push_back(i);
665 // XXX(clang-tidy): https://bugs.llvm.org/show_bug.cgi?id=44165
666 // NOLINTNEXTLINE(bugprone-branch-clone)
667 } else if (args[i] == "CONFIG") {
668 configArgs.push_back(i);
670 // XXX(clang-tidy): https://bugs.llvm.org/show_bug.cgi?id=44165
671 // NOLINTNEXTLINE(bugprone-branch-clone)
672 } else if (args[i] == "NO_MODULE") {
673 configArgs.push_back(i);
675 } else if (args[i] == "REQUIRED") {
676 this->Required = true;
677 doing = DoingComponents;
678 } else if (args[i] == "COMPONENTS") {
679 doing = DoingComponents;
680 } else if (args[i] == "OPTIONAL_COMPONENTS") {
681 doing = DoingOptionalComponents;
682 } else if (args[i] == "NAMES") {
683 configArgs.push_back(i);
685 } else if (args[i] == "PATHS") {
686 configArgs.push_back(i);
688 } else if (args[i] == "HINTS") {
689 configArgs.push_back(i);
691 } else if (args[i] == "PATH_SUFFIXES") {
692 configArgs.push_back(i);
693 doing = DoingPathSuffixes;
694 } else if (args[i] == "CONFIGS") {
695 configArgs.push_back(i);
696 doing = DoingConfigs;
697 } else if (args[i] == "NO_POLICY_SCOPE") {
698 this->PolicyScope = false;
700 } else if (args[i] == "NO_CMAKE_PACKAGE_REGISTRY") {
701 this->NoUserRegistry = true;
702 configArgs.push_back(i);
704 } else if (args[i] == "NO_CMAKE_SYSTEM_PACKAGE_REGISTRY") {
705 this->NoSystemRegistry = true;
706 configArgs.push_back(i);
708 // XXX(clang-tidy): https://bugs.llvm.org/show_bug.cgi?id=44165
709 // NOLINTNEXTLINE(bugprone-branch-clone)
710 } else if (args[i] == "NO_CMAKE_BUILDS_PATH") {
711 // Ignore legacy option.
712 configArgs.push_back(i);
714 } else if (args[i] == "REGISTRY_VIEW") {
715 if (++i == args.size()) {
716 this->SetError("missing required argument for \"REGISTRY_VIEW\"");
719 auto view = cmWindowsRegistry::ToView(args[i]);
721 this->RegistryView = *view;
722 this->RegistryViewDefined = true;
725 cmStrCat("given invalid value for \"REGISTRY_VIEW\": ", args[i]));
728 } else if (this->CheckCommonArgument(args[i])) {
729 configArgs.push_back(i);
731 } else if ((doing == DoingComponents) ||
732 (doing == DoingOptionalComponents)) {
733 // Set a variable telling the find script whether this component
735 const char* isRequired = "1";
736 if (doing == DoingOptionalComponents) {
738 optionalComponents.insert(args[i]);
740 requiredComponents.insert(args[i]);
743 componentVarDefs.emplace_back(this->Name + "_FIND_REQUIRED_" + args[i],
746 // Append to the list of required components.
747 components += components_sep;
748 components += args[i];
749 components_sep = ";";
750 } else if (doing == DoingNames) {
751 this->Names.push_back(args[i]);
752 } else if (doing == DoingPaths) {
753 this->UserGuessArgs.push_back(args[i]);
754 } else if (doing == DoingHints) {
755 this->UserHintsArgs.push_back(args[i]);
756 } else if (doing == DoingPathSuffixes) {
757 this->AddPathSuffix(args[i]);
758 } else if (doing == DoingConfigs) {
759 if (args[i].find_first_of(":/\\") != std::string::npos ||
760 cmSystemTools::GetFilenameLastExtension(args[i]) != ".cmake") {
761 this->SetError(cmStrCat(
762 "given CONFIGS option followed by invalid file name \"", args[i],
763 "\". The names given must be file names without "
764 "a path and with a \".cmake\" extension."));
767 this->Configs.push_back(args[i]);
768 } else if (!haveVersion && versionRegex.find(args[i])) {
770 this->VersionComplete = args[i];
773 cmStrCat("called with invalid argument \"", args[i], "\""));
778 if (!this->GlobalScope) {
780 this->Makefile->GetDefinition("CMAKE_FIND_PACKAGE_TARGETS_GLOBAL"));
781 this->GlobalScope = value.IsOn();
784 std::vector<std::string> doubledComponents;
785 std::set_intersection(requiredComponents.begin(), requiredComponents.end(),
786 optionalComponents.begin(), optionalComponents.end(),
787 std::back_inserter(doubledComponents));
788 if (!doubledComponents.empty()) {
790 cmStrCat("called with components that are both required and "
792 cmWrap(" ", doubledComponents, "", "\n"), "\n"));
796 // Check and eliminate search modes not allowed by the args provided
797 this->UseFindModules = configArgs.empty();
798 this->UseConfigFiles = moduleArgs.empty();
799 if (!this->UseFindModules && !this->UseConfigFiles) {
800 std::ostringstream e;
801 e << "given options exclusive to Module mode:\n";
802 for (auto si : moduleArgs) {
803 e << " " << args[si] << "\n";
805 e << "and options exclusive to Config mode:\n";
806 for (auto si : configArgs) {
807 e << " " << args[si] << "\n";
809 e << "The options are incompatible.";
810 this->SetError(e.str());
814 // Ignore EXACT with no version.
815 if (this->VersionComplete.empty() && this->VersionExact) {
816 this->VersionExact = false;
817 this->Makefile->IssueMessage(
818 MessageType::AUTHOR_WARNING,
819 "Ignoring EXACT since no version is requested.");
822 if (this->VersionComplete.empty() || components.empty()) {
823 // Check whether we are recursing inside "Find<name>.cmake" within
824 // another find_package(<name>) call.
825 std::string const mod = cmStrCat(this->Name, "_FIND_MODULE");
826 if (this->Makefile->IsOn(mod)) {
827 if (this->VersionComplete.empty()) {
828 // Get version information from the outer call if necessary.
829 // Requested version string.
830 std::string const ver = cmStrCat(this->Name, "_FIND_VERSION_COMPLETE");
831 this->VersionComplete = this->Makefile->GetSafeDefinition(ver);
833 // Whether an exact version is required.
834 std::string const exact = cmStrCat(this->Name, "_FIND_VERSION_EXACT");
835 this->VersionExact = this->Makefile->IsOn(exact);
837 if (components.empty()) {
838 std::string const components_var = this->Name + "_FIND_COMPONENTS";
839 components = this->Makefile->GetSafeDefinition(components_var);
844 // fill various parts of version specification
845 if (!this->VersionComplete.empty()) {
846 if (!versionRegex.find(this->VersionComplete)) {
847 this->SetError("called with invalid version specification.");
851 this->Version = versionRegex.match(1);
852 this->VersionMax = versionRegex.match(5);
853 if (versionRegex.match(4) == "<"_s) {
854 this->VersionRangeMax = VERSION_ENDPOINT_EXCLUDED;
856 if (!this->VersionMax.empty()) {
857 this->VersionRange = this->VersionComplete;
861 if (!this->VersionRange.empty()) {
862 // version range must not be empty
863 if ((this->VersionRangeMax == VERSION_ENDPOINT_INCLUDED &&
864 cmSystemTools::VersionCompareGreater(this->Version,
865 this->VersionMax)) ||
866 (this->VersionRangeMax == VERSION_ENDPOINT_EXCLUDED &&
867 cmSystemTools::VersionCompareGreaterEq(this->Version,
868 this->VersionMax))) {
869 this->SetError("specified version range is empty.");
874 if (this->VersionExact && !this->VersionRange.empty()) {
875 this->SetError("EXACT cannot be specified with a version range.");
879 if (!this->Version.empty()) {
881 parseVersion(this->Version, this->VersionMajor, this->VersionMinor,
882 this->VersionPatch, this->VersionTweak);
884 if (!this->VersionMax.empty()) {
885 this->VersionMaxCount = parseVersion(
886 this->VersionMax, this->VersionMaxMajor, this->VersionMaxMinor,
887 this->VersionMaxPatch, this->VersionMaxTweak);
890 const std::string makePackageRequiredVar =
891 cmStrCat("CMAKE_REQUIRE_FIND_PACKAGE_", this->Name);
892 const bool makePackageRequiredSet =
893 this->Makefile->IsOn(makePackageRequiredVar);
894 if (makePackageRequiredSet) {
895 if (this->Required) {
896 this->Makefile->IssueMessage(
897 MessageType::WARNING,
898 cmStrCat("for module ", this->Name,
899 " already called with REQUIRED, thus ",
900 makePackageRequiredVar, " has no effect."));
902 this->Required = true;
906 std::string const disableFindPackageVar =
907 cmStrCat("CMAKE_DISABLE_FIND_PACKAGE_", this->Name);
908 if (this->Makefile->IsOn(disableFindPackageVar)) {
909 if (this->Required) {
911 cmStrCat("for module ", this->Name,
912 (makePackageRequiredSet
913 ? " was made REQUIRED with " + makePackageRequiredVar
914 : " called with REQUIRED, "),
915 " but ", disableFindPackageVar,
916 " is enabled. A REQUIRED package cannot be disabled."));
922 // Now choose what method(s) we will use to satisfy the request. Note that
923 // we still want all the above checking of arguments, etc. regardless of the
924 // method used. This will ensure ill-formed arguments are caught earlier,
925 // before things like dependency providers need to deal with them.
927 // A dependency provider (if set) gets first look before other methods.
928 // We do this before modifying the package root path stack because a
929 // provider might use methods that ignore that.
930 cmState* const state = this->Makefile->GetState();
931 cmState::Command const providerCommand = state->GetDependencyProviderCommand(
932 cmDependencyProvider::Method::FindPackage);
933 if (bypassProvider) {
934 if (this->DebugMode && providerCommand) {
936 "BYPASS_PROVIDER given, skipping dependency provider");
938 } else if (providerCommand) {
939 if (this->DebugMode) {
940 this->DebugMessage(cmStrCat("Trying dependency provider command: ",
941 state->GetDependencyProvider()->GetCommand(),
944 std::vector<cmListFileArgument> listFileArgs(args.size() + 1);
946 cmListFileArgument("FIND_PACKAGE", cmListFileArgument::Unquoted, 0);
947 std::transform(args.begin(), args.end(), listFileArgs.begin() + 1,
948 [](const std::string& arg) {
949 return cmListFileArgument(arg,
950 cmListFileArgument::Bracket, 0);
952 if (!providerCommand(listFileArgs, this->Status)) {
955 if (this->Makefile->IsOn(cmStrCat(this->Name, "_FOUND"))) {
956 if (this->DebugMode) {
957 this->DebugMessage("Package was found by the dependency provider");
959 this->AppendSuccessInformation();
965 // Allocate a PACKAGE_ROOT_PATH for the current find_package call.
966 this->Makefile->FindPackageRootPathStack.emplace_back();
967 std::vector<std::string>& rootPaths =
968 this->Makefile->FindPackageRootPathStack.back();
970 // Add root paths from <PackageName>_ROOT CMake and environment variables,
971 // subject to CMP0074.
972 switch (this->Makefile->GetPolicyStatus(cmPolicies::CMP0074)) {
973 case cmPolicies::WARN:
974 this->Makefile->MaybeWarnCMP0074(this->Name);
976 case cmPolicies::OLD:
977 // OLD behavior is to ignore the <pkg>_ROOT variables.
979 case cmPolicies::REQUIRED_IF_USED:
980 case cmPolicies::REQUIRED_ALWAYS:
981 this->Makefile->IssueMessage(
982 MessageType::FATAL_ERROR,
983 cmPolicies::GetRequiredPolicyError(cmPolicies::CMP0074));
985 case cmPolicies::NEW: {
986 // NEW behavior is to honor the <pkg>_ROOT variables.
987 std::string const rootVar = this->Name + "_ROOT";
988 this->Makefile->GetDefExpandList(rootVar, rootPaths, false);
989 cmSystemTools::GetPath(rootPaths, rootVar.c_str());
994 this->SetModuleVariables(components, componentVarDefs);
996 // See if we have been told to delegate to FetchContent or some other
997 // redirected config package first. We have to check all names that
998 // find_package() may look for, but only need to invoke the override for the
999 // first one that matches.
1000 auto overrideNames = this->Names;
1001 if (overrideNames.empty()) {
1002 overrideNames.push_back(this->Name);
1004 bool forceConfigMode = false;
1005 const auto redirectsDir =
1006 this->Makefile->GetSafeDefinition("CMAKE_FIND_PACKAGE_REDIRECTS_DIR");
1007 for (const auto& overrideName : overrideNames) {
1008 const auto nameLower = cmSystemTools::LowerCase(overrideName);
1009 const auto delegatePropName =
1010 cmStrCat("_FetchContent_", nameLower, "_override_find_package");
1011 const cmValue delegateToFetchContentProp =
1012 this->Makefile->GetState()->GetGlobalProperty(delegatePropName);
1013 if (delegateToFetchContentProp.IsOn()) {
1014 // When this property is set, the FetchContent module has already been
1015 // included at least once, so we know the FetchContent_MakeAvailable()
1016 // command will be defined. Any future find_package() calls after this
1017 // one for this package will by-pass this once-only delegation.
1018 // The following call will typically create a <name>-config.cmake file
1019 // in the redirectsDir, which we still want to process like any other
1020 // config file to ensure we follow normal find_package() processing.
1021 cmListFileFunction func(
1022 "FetchContent_MakeAvailable", 0, 0,
1023 { cmListFileArgument(overrideName, cmListFileArgument::Unquoted, 0) });
1024 if (!this->Makefile->ExecuteCommand(func, this->Status)) {
1029 if (cmSystemTools::FileExists(
1030 cmStrCat(redirectsDir, '/', nameLower, "-config.cmake")) ||
1031 cmSystemTools::FileExists(
1032 cmStrCat(redirectsDir, '/', overrideName, "Config.cmake"))) {
1033 // Force the use of this redirected config package file, regardless of
1034 // the type of find_package() call. Files in the redirectsDir must always
1035 // take priority over everything else.
1036 forceConfigMode = true;
1037 this->UseConfigFiles = true;
1038 this->UseFindModules = false;
1039 this->Names.clear();
1040 this->Names.emplace_back(overrideName); // Force finding this one
1041 this->Variable = cmStrCat(this->Name, "_DIR");
1042 this->SetConfigDirCacheVariable(redirectsDir);
1047 // See if there is a Find<PackageName>.cmake module.
1048 bool loadedPackage = false;
1049 if (forceConfigMode) {
1050 loadedPackage = this->FindPackageUsingConfigMode();
1051 } else if (this->Makefile->IsOn("CMAKE_FIND_PACKAGE_PREFER_CONFIG")) {
1052 if (this->UseConfigFiles && this->FindPackageUsingConfigMode()) {
1053 loadedPackage = true;
1055 if (this->FindPackageUsingModuleMode()) {
1056 loadedPackage = true;
1058 // The package was not loaded. Report errors.
1059 if (this->HandlePackageMode(HandlePackageModeType::Module)) {
1060 loadedPackage = true;
1065 if (this->UseFindModules && this->FindPackageUsingModuleMode()) {
1066 loadedPackage = true;
1068 // Handle CMAKE_FIND_PACKAGE_WARN_NO_MODULE (warn when CONFIG mode is
1069 // implicitly assumed)
1070 if (this->UseFindModules && this->UseConfigFiles &&
1071 this->Makefile->IsOn("CMAKE_FIND_PACKAGE_WARN_NO_MODULE")) {
1072 std::ostringstream aw;
1073 if (this->RequiredCMakeVersion >= CMake_VERSION_ENCODE(2, 8, 8)) {
1074 aw << "find_package called without either MODULE or CONFIG option "
1078 << ".cmake module is in CMAKE_MODULE_PATH. "
1079 "Add MODULE to exclusively request Module mode and fail if "
1082 << ".cmake is missing. "
1083 "Add CONFIG to exclusively request Config mode and search for "
1085 "package configuration file provided by "
1086 << this->Name << " (" << this->Name << "Config.cmake or "
1087 << cmSystemTools::LowerCase(this->Name) << "-config.cmake). ";
1089 aw << "find_package called without NO_MODULE option and no "
1092 << ".cmake module is in CMAKE_MODULE_PATH. "
1093 "Add NO_MODULE to exclusively request Config mode and search "
1095 "package configuration file provided by "
1096 << this->Name << " (" << this->Name << "Config.cmake or "
1097 << cmSystemTools::LowerCase(this->Name)
1098 << "-config.cmake). Otherwise make Find" << this->Name
1099 << ".cmake available in CMAKE_MODULE_PATH.";
1102 "(Variable CMAKE_FIND_PACKAGE_WARN_NO_MODULE enabled this "
1104 this->Makefile->IssueMessage(MessageType::AUTHOR_WARNING, aw.str());
1107 if (this->FindPackageUsingConfigMode()) {
1108 loadedPackage = true;
1113 this->AppendSuccessInformation();
1115 // Restore original state of "_FIND_" variables set in SetModuleVariables()
1116 this->RestoreFindDefinitions();
1118 // Pop the package stack
1119 this->Makefile->FindPackageRootPathStack.pop_back();
1121 if (!this->DebugBuffer.empty()) {
1122 this->DebugMessage(this->DebugBuffer);
1125 return loadedPackage;
1128 bool cmFindPackageCommand::FindPackageUsingModuleMode()
1130 bool foundModule = false;
1131 if (!this->FindModule(foundModule)) {
1137 bool cmFindPackageCommand::FindPackageUsingConfigMode()
1139 this->Variable = cmStrCat(this->Name, "_DIR");
1141 // Add the default name.
1142 if (this->Names.empty()) {
1143 this->Names.push_back(this->Name);
1146 // Add the default configs.
1147 if (this->Configs.empty()) {
1148 for (std::string const& n : this->Names) {
1149 std::string config = cmStrCat(n, "Config.cmake");
1150 this->Configs.push_back(config);
1152 config = cmStrCat(cmSystemTools::LowerCase(n), "-config.cmake");
1153 this->Configs.push_back(std::move(config));
1157 // get igonored paths from vars and reroot them.
1158 std::vector<std::string> ignored;
1159 this->GetIgnoredPaths(ignored);
1160 this->RerootPaths(ignored);
1162 // Construct a set of ignored paths
1163 this->IgnoredPaths.clear();
1164 this->IgnoredPaths.insert(ignored.begin(), ignored.end());
1166 // get igonored prefix paths from vars and reroot them.
1167 std::vector<std::string> ignoredPrefixes;
1168 this->GetIgnoredPrefixPaths(ignoredPrefixes);
1169 this->RerootPaths(ignoredPrefixes);
1171 // Construct a set of ignored prefix paths
1172 this->IgnoredPrefixPaths.clear();
1173 this->IgnoredPrefixPaths.insert(ignoredPrefixes.begin(),
1174 ignoredPrefixes.end());
1176 // Find and load the package.
1177 return this->HandlePackageMode(HandlePackageModeType::Config);
1180 void cmFindPackageCommand::SetVersionVariables(
1181 const std::function<void(const std::string&, cm::string_view)>&
1183 const std::string& prefix, const std::string& version,
1184 const unsigned int count, const unsigned int major, const unsigned int minor,
1185 const unsigned int patch, const unsigned int tweak)
1187 addDefinition(prefix, version);
1190 snprintf(buf, sizeof(buf), "%u", major);
1191 addDefinition(prefix + "_MAJOR", buf);
1192 snprintf(buf, sizeof(buf), "%u", minor);
1193 addDefinition(prefix + "_MINOR", buf);
1194 snprintf(buf, sizeof(buf), "%u", patch);
1195 addDefinition(prefix + "_PATCH", buf);
1196 snprintf(buf, sizeof(buf), "%u", tweak);
1197 addDefinition(prefix + "_TWEAK", buf);
1198 snprintf(buf, sizeof(buf), "%u", count);
1199 addDefinition(prefix + "_COUNT", buf);
1202 void cmFindPackageCommand::SetModuleVariables(
1203 const std::string& components,
1204 const std::vector<std::pair<std::string, const char*>>& componentVarDefs)
1206 this->AddFindDefinition("CMAKE_FIND_PACKAGE_NAME", this->Name);
1208 // Store the list of components and associated variable definitions
1209 std::string components_var = this->Name + "_FIND_COMPONENTS";
1210 this->AddFindDefinition(components_var, components);
1211 for (const auto& varDef : componentVarDefs) {
1212 this->AddFindDefinition(varDef.first, varDef.second);
1216 // Tell the module that is about to be read that it should find
1218 std::string quietly = cmStrCat(this->Name, "_FIND_QUIETLY");
1219 this->AddFindDefinition(quietly, "1"_s);
1222 if (this->Required) {
1223 // Tell the module that is about to be read that it should report
1224 // a fatal error if the package is not found.
1225 std::string req = cmStrCat(this->Name, "_FIND_REQUIRED");
1226 this->AddFindDefinition(req, "1"_s);
1229 if (!this->VersionComplete.empty()) {
1230 std::string req = cmStrCat(this->Name, "_FIND_VERSION_COMPLETE");
1231 this->AddFindDefinition(req, this->VersionComplete);
1234 // Tell the module that is about to be read what version of the
1235 // package has been requested.
1236 auto addDefinition = [this](const std::string& variable,
1237 cm::string_view value) {
1238 this->AddFindDefinition(variable, value);
1241 if (!this->Version.empty()) {
1242 auto prefix = cmStrCat(this->Name, "_FIND_VERSION"_s);
1243 this->SetVersionVariables(addDefinition, prefix, this->Version,
1244 this->VersionCount, this->VersionMajor,
1245 this->VersionMinor, this->VersionPatch,
1246 this->VersionTweak);
1248 // Tell the module whether an exact version has been requested.
1249 auto exact = cmStrCat(this->Name, "_FIND_VERSION_EXACT");
1250 this->AddFindDefinition(exact, this->VersionExact ? "1"_s : "0"_s);
1252 if (!this->VersionRange.empty()) {
1253 auto prefix = cmStrCat(this->Name, "_FIND_VERSION_MIN"_s);
1254 this->SetVersionVariables(addDefinition, prefix, this->Version,
1255 this->VersionCount, this->VersionMajor,
1256 this->VersionMinor, this->VersionPatch,
1257 this->VersionTweak);
1259 prefix = cmStrCat(this->Name, "_FIND_VERSION_MAX"_s);
1260 this->SetVersionVariables(addDefinition, prefix, this->VersionMax,
1261 this->VersionMaxCount, this->VersionMaxMajor,
1262 this->VersionMaxMinor, this->VersionMaxPatch,
1263 this->VersionMaxTweak);
1265 auto id = cmStrCat(this->Name, "_FIND_VERSION_RANGE");
1266 this->AddFindDefinition(id, this->VersionRange);
1267 id = cmStrCat(this->Name, "_FIND_VERSION_RANGE_MIN");
1268 this->AddFindDefinition(id, this->VersionRangeMin);
1269 id = cmStrCat(this->Name, "_FIND_VERSION_RANGE_MAX");
1270 this->AddFindDefinition(id, this->VersionRangeMax);
1273 if (this->RegistryViewDefined) {
1274 this->AddFindDefinition(cmStrCat(this->Name, "_FIND_REGISTRY_VIEW"),
1275 cmWindowsRegistry::FromView(this->RegistryView));
1279 void cmFindPackageCommand::AddFindDefinition(const std::string& var,
1280 const cm::string_view value)
1282 if (cmValue old = this->Makefile->GetDefinition(var)) {
1283 this->OriginalDefs[var].exists = true;
1284 this->OriginalDefs[var].value = *old;
1286 this->OriginalDefs[var].exists = false;
1288 this->Makefile->AddDefinition(var, value);
1291 void cmFindPackageCommand::RestoreFindDefinitions()
1293 for (auto const& i : this->OriginalDefs) {
1294 OriginalDef const& od = i.second;
1296 this->Makefile->AddDefinition(i.first, od.value);
1298 this->Makefile->RemoveDefinition(i.first);
1303 bool cmFindPackageCommand::FindModule(bool& found)
1305 std::string moduleFileName = cmStrCat("Find", this->Name, ".cmake");
1307 bool system = false;
1308 std::string debugBuffer = cmStrCat(
1309 "find_package considered the following paths for ", moduleFileName, ":\n");
1310 std::string mfile = this->Makefile->GetModulesFile(
1311 moduleFileName, system, this->DebugMode, debugBuffer);
1312 if (this->DebugMode) {
1313 if (mfile.empty()) {
1314 debugBuffer = cmStrCat(debugBuffer, "The file was not found.\n");
1317 cmStrCat(debugBuffer, "The file was found at\n ", mfile, "\n");
1319 this->DebugBuffer = cmStrCat(this->DebugBuffer, debugBuffer);
1322 if (!mfile.empty()) {
1324 auto const it = this->DeprecatedFindModules.find(this->Name);
1325 if (it != this->DeprecatedFindModules.end()) {
1326 cmPolicies::PolicyStatus status =
1327 this->Makefile->GetPolicyStatus(it->second);
1329 case cmPolicies::WARN: {
1330 this->Makefile->IssueMessage(
1331 MessageType::AUTHOR_WARNING,
1332 cmStrCat(cmPolicies::GetPolicyWarning(it->second), "\n"));
1335 case cmPolicies::OLD:
1337 case cmPolicies::REQUIRED_IF_USED:
1338 case cmPolicies::REQUIRED_ALWAYS:
1339 case cmPolicies::NEW:
1345 // Load the module we found, and set "<name>_FIND_MODULE" to true
1348 std::string const var = cmStrCat(this->Name, "_FIND_MODULE");
1349 this->Makefile->AddDefinition(var, "1");
1350 bool result = this->ReadListFile(mfile, DoPolicyScope);
1351 this->Makefile->RemoveDefinition(var);
1353 if (this->DebugMode) {
1354 std::string const foundVar = cmStrCat(this->Name, "_FOUND");
1355 if (this->Makefile->IsDefinitionSet(foundVar) &&
1356 !this->Makefile->IsOn(foundVar)) {
1358 this->DebugBuffer = cmStrCat(
1359 this->DebugBuffer, "The module is considered not found due to ",
1360 foundVar, " being FALSE.");
1368 bool cmFindPackageCommand::HandlePackageMode(
1369 const HandlePackageModeType handlePackageModeType)
1371 this->ConsideredConfigs.clear();
1373 // Try to find the config file.
1374 cmValue def = this->Makefile->GetDefinition(this->Variable);
1376 // Try to load the config file if the directory is known
1377 bool fileFound = false;
1378 if (this->UseConfigFiles) {
1379 if (!cmIsOff(def)) {
1380 // Get the directory from the variable value.
1381 std::string dir = *def;
1382 cmSystemTools::ConvertToUnixSlashes(dir);
1384 // Treat relative paths with respect to the current source dir.
1385 if (!cmSystemTools::FileIsFullPath(dir)) {
1387 dir = this->Makefile->GetCurrentSourceDirectory() + dir;
1389 // The file location was cached. Look for the correct file.
1391 if (this->FindConfigFile(dir, file)) {
1392 this->FileFound = file;
1395 def = this->Makefile->GetDefinition(this->Variable);
1398 // Search for the config file if it is not already found.
1399 if (cmIsOff(def) || !fileFound) {
1400 fileFound = this->FindConfig();
1404 if (fileFound && this->FileFound.empty()) {
1405 this->Makefile->IssueMessage(
1406 MessageType::INTERNAL_ERROR,
1407 "fileFound is true but FileFound is empty!");
1412 std::string const foundVar = cmStrCat(this->Name, "_FOUND");
1413 std::string const notFoundMessageVar =
1414 cmStrCat(this->Name, "_NOT_FOUND_MESSAGE");
1415 std::string notFoundMessage;
1417 // If the directory for the config file was found, try to read the file.
1420 bool configFileSetFOUNDFalse = false;
1423 if (this->Makefile->IsDefinitionSet(foundVar) &&
1424 !this->Makefile->IsOn(foundVar)) {
1425 // by removing Foo_FOUND here if it is FALSE, we don't really change
1426 // the situation for the Config file which is about to be included,
1427 // but we make it possible to detect later on whether the Config file
1428 // has set Foo_FOUND to FALSE itself:
1429 this->Makefile->RemoveDefinition(foundVar);
1431 this->Makefile->RemoveDefinition(notFoundMessageVar);
1433 // Set the version variables before loading the config file.
1434 // It may override them.
1435 this->StoreVersionFound();
1437 // Parse the configuration file.
1438 if (this->ReadListFile(this->FileFound, DoPolicyScope)) {
1439 // The package has been found.
1442 // Check whether the Config file has set Foo_FOUND to FALSE:
1443 if (this->Makefile->IsDefinitionSet(foundVar) &&
1444 !this->Makefile->IsOn(foundVar)) {
1445 // we get here if the Config file has set Foo_FOUND actively to FALSE
1447 configFileSetFOUNDFalse = true;
1449 this->Makefile->GetSafeDefinition(notFoundMessageVar);
1452 // The configuration file is invalid.
1457 if (this->UseFindModules && !found &&
1458 handlePackageModeType == HandlePackageModeType::Config &&
1459 this->Makefile->IsOn("CMAKE_FIND_PACKAGE_PREFER_CONFIG")) {
1460 // Config mode failed. Allow Module case.
1464 // package not found
1465 if (result && !found) {
1466 // warn if package required or neither quiet nor in config mode
1467 if (this->Required ||
1469 (this->UseConfigFiles && !this->UseFindModules &&
1470 this->ConsideredConfigs.empty()))) {
1471 // The variable is not set.
1472 std::ostringstream e;
1473 std::ostringstream aw;
1474 if (configFileSetFOUNDFalse) {
1475 /* clang-format off */
1476 e << "Found package configuration file:\n"
1477 " " << this->FileFound << "\n"
1478 "but it set " << foundVar << " to FALSE so package \"" <<
1479 this->Name << "\" is considered to be NOT FOUND.";
1480 /* clang-format on */
1481 if (!notFoundMessage.empty()) {
1482 e << " Reason given by package: \n" << notFoundMessage << "\n";
1485 // If there are files in ConsideredConfigs, it means that FooConfig.cmake
1486 // have been found, but they didn't have appropriate versions.
1487 else if (!this->ConsideredConfigs.empty()) {
1488 auto duplicate_end = cmRemoveDuplicates(this->ConsideredConfigs);
1489 e << "Could not find a configuration file for package \"" << this->Name
1491 << (this->VersionExact ? "exactly matches" : "is compatible with")
1492 << " requested version "
1493 << (this->VersionRange.empty() ? "" : "range ") << "\""
1494 << this->VersionComplete
1496 "The following configuration files were considered but not "
1499 for (ConfigFileInfo const& info :
1500 cmMakeRange(this->ConsideredConfigs.cbegin(), duplicate_end)) {
1501 e << " " << info.filename << ", version: " << info.version << "\n";
1504 std::string requestedVersionString;
1505 if (!this->VersionComplete.empty()) {
1506 requestedVersionString =
1507 cmStrCat(" (requested version ", this->VersionComplete, ')');
1510 if (this->UseConfigFiles) {
1511 if (this->UseFindModules) {
1512 e << "By not providing \"Find" << this->Name
1514 "CMAKE_MODULE_PATH this project has asked CMake to find a "
1515 "package configuration file provided by \""
1518 "but CMake did not find one.\n";
1521 if (this->Configs.size() == 1) {
1522 e << "Could not find a package configuration file named \""
1523 << this->Configs[0] << "\" provided by package \"" << this->Name
1524 << "\"" << requestedVersionString << ".\n";
1526 e << "Could not find a package configuration file provided by \""
1527 << this->Name << "\"" << requestedVersionString
1528 << " with any of the following names:\n"
1529 << cmWrap(" ", this->Configs, "", "\n") << "\n";
1532 e << "Add the installation prefix of \"" << this->Name
1534 "CMAKE_PREFIX_PATH or set \""
1537 "directory containing one of the above files. "
1540 << "\" provides a separate development "
1541 "package or SDK, be sure it has been installed.";
1542 } else // if(!this->UseFindModules && !this->UseConfigFiles)
1544 e << "No \"Find" << this->Name
1545 << ".cmake\" found in "
1546 "CMAKE_MODULE_PATH.";
1549 << "Find" << this->Name
1550 << ".cmake must either be part of this "
1551 "project itself, in this case adjust CMAKE_MODULE_PATH so that "
1552 "it points to the correct location inside its source tree.\n"
1553 "Or it must be installed by a package which has already been "
1554 "found via find_package(). In this case make sure that "
1555 "package has indeed been found and adjust CMAKE_MODULE_PATH to "
1556 "contain the location where that package has installed "
1559 << ".cmake. This must be a location "
1560 "provided by that package. This error in general means that "
1561 "the buildsystem of this project is relying on a Find-module "
1562 "without ensuring that it is actually available.\n";
1566 this->Makefile->IssueMessage(this->Required ? MessageType::FATAL_ERROR
1567 : MessageType::WARNING,
1569 if (this->Required) {
1570 cmSystemTools::SetFatalErrorOccurred();
1573 if (!aw.str().empty()) {
1574 this->Makefile->IssueMessage(MessageType::AUTHOR_WARNING, aw.str());
1577 // output result if in config mode but not in quiet mode
1578 else if (!this->Quiet) {
1579 this->Makefile->DisplayStatus(cmStrCat("Could NOT find ", this->Name,
1580 " (missing: ", this->Name,
1586 // Set a variable marking whether the package was found.
1587 this->Makefile->AddDefinition(foundVar, found ? "1" : "0");
1589 // Set a variable naming the configuration file that was found.
1590 std::string const fileVar = cmStrCat(this->Name, "_CONFIG");
1592 this->Makefile->AddDefinition(fileVar, this->FileFound);
1594 this->Makefile->RemoveDefinition(fileVar);
1597 std::string const consideredConfigsVar =
1598 cmStrCat(this->Name, "_CONSIDERED_CONFIGS");
1599 std::string const consideredVersionsVar =
1600 cmStrCat(this->Name, "_CONSIDERED_VERSIONS");
1602 std::string consideredConfigFiles;
1603 std::string consideredVersions;
1605 const char* sep = "";
1606 for (ConfigFileInfo const& i : this->ConsideredConfigs) {
1607 consideredConfigFiles += sep;
1608 consideredVersions += sep;
1609 consideredConfigFiles += i.filename;
1610 consideredVersions += i.version;
1614 this->Makefile->AddDefinition(consideredConfigsVar, consideredConfigFiles);
1616 this->Makefile->AddDefinition(consideredVersionsVar, consideredVersions);
1621 bool cmFindPackageCommand::FindConfig()
1623 // Compute the set of search prefixes.
1624 this->ComputePrefixes();
1626 // Look for the project's configuration file.
1628 if (this->DebugMode) {
1629 this->DebugBuffer = cmStrCat(this->DebugBuffer,
1630 "find_package considered the following "
1632 this->Name, "'s Config module:\n");
1635 // Search for frameworks.
1636 if (!found && (this->SearchFrameworkFirst || this->SearchFrameworkOnly)) {
1637 found = this->FindFrameworkConfig();
1641 if (!found && (this->SearchAppBundleFirst || this->SearchAppBundleOnly)) {
1642 found = this->FindAppBundleConfig();
1646 if (!found && !(this->SearchFrameworkOnly || this->SearchAppBundleOnly)) {
1647 found = this->FindPrefixedConfig();
1650 // Search for frameworks.
1651 if (!found && this->SearchFrameworkLast) {
1652 found = this->FindFrameworkConfig();
1656 if (!found && this->SearchAppBundleLast) {
1657 found = this->FindAppBundleConfig();
1660 if (this->DebugMode) {
1662 this->DebugBuffer = cmStrCat(
1663 this->DebugBuffer, "The file was found at\n ", this->FileFound, "\n");
1666 cmStrCat(this->DebugBuffer, "The file was not found.\n");
1670 // Store the entry in the cache so it can be set by the user.
1673 init = cmSystemTools::GetFilenamePath(this->FileFound);
1675 init = this->Variable + "-NOTFOUND";
1677 // We force the value since we do not get here if it was already set.
1678 this->SetConfigDirCacheVariable(init);
1683 void cmFindPackageCommand::SetConfigDirCacheVariable(const std::string& value)
1685 std::string const help =
1686 cmStrCat("The directory containing a CMake configuration file for ",
1688 this->Makefile->AddCacheDefinition(this->Variable, value, help.c_str(),
1689 cmStateEnums::PATH, true);
1690 if (this->Makefile->GetPolicyStatus(cmPolicies::CMP0126) ==
1692 this->Makefile->IsNormalDefinitionSet(this->Variable)) {
1693 this->Makefile->AddDefinition(this->Variable, value);
1697 bool cmFindPackageCommand::FindPrefixedConfig()
1699 std::vector<std::string> const& prefixes = this->SearchPaths;
1701 prefixes.begin(), prefixes.end(),
1702 [this](std::string const& p) -> bool { return this->SearchPrefix(p); });
1705 bool cmFindPackageCommand::FindFrameworkConfig()
1707 std::vector<std::string> const& prefixes = this->SearchPaths;
1708 return std::any_of(prefixes.begin(), prefixes.end(),
1709 [this](std::string const& p) -> bool {
1710 return this->SearchFrameworkPrefix(p);
1714 bool cmFindPackageCommand::FindAppBundleConfig()
1716 std::vector<std::string> const& prefixes = this->SearchPaths;
1717 return std::any_of(prefixes.begin(), prefixes.end(),
1718 [this](std::string const& p) -> bool {
1719 return this->SearchAppBundlePrefix(p);
1723 bool cmFindPackageCommand::ReadListFile(const std::string& f,
1724 const PolicyScopeRule psr)
1726 const bool noPolicyScope = !this->PolicyScope || psr == NoPolicyScope;
1728 using ITScope = cmMakefile::ImportedTargetScope;
1729 ITScope scope = this->GlobalScope ? ITScope::Global : ITScope::Local;
1730 cmMakefile::SetGlobalTargetImportScope globScope(this->Makefile, scope);
1732 if (this->Makefile->ReadDependentFile(f, noPolicyScope)) {
1735 std::string const e = cmStrCat("Error reading CMake code from \"", f, "\".");
1740 void cmFindPackageCommand::AppendToFoundProperty(const bool found)
1742 std::vector<std::string> foundContents;
1744 this->Makefile->GetState()->GetGlobalProperty("PACKAGES_FOUND");
1745 if (cmNonempty(foundProp)) {
1746 cmExpandList(*foundProp, foundContents, false);
1748 std::find(foundContents.begin(), foundContents.end(), this->Name);
1749 if (nameIt != foundContents.end()) {
1750 foundContents.erase(nameIt);
1754 std::vector<std::string> notFoundContents;
1755 cmValue notFoundProp =
1756 this->Makefile->GetState()->GetGlobalProperty("PACKAGES_NOT_FOUND");
1757 if (cmNonempty(notFoundProp)) {
1758 cmExpandList(*notFoundProp, notFoundContents, false);
1760 std::find(notFoundContents.begin(), notFoundContents.end(), this->Name);
1761 if (nameIt != notFoundContents.end()) {
1762 notFoundContents.erase(nameIt);
1767 foundContents.push_back(this->Name);
1769 notFoundContents.push_back(this->Name);
1772 std::string tmp = cmJoin(foundContents, ";");
1773 this->Makefile->GetState()->SetGlobalProperty("PACKAGES_FOUND", tmp.c_str());
1775 tmp = cmJoin(notFoundContents, ";");
1776 this->Makefile->GetState()->SetGlobalProperty("PACKAGES_NOT_FOUND",
1780 void cmFindPackageCommand::AppendSuccessInformation()
1783 std::string const transitivePropName =
1784 cmStrCat("_CMAKE_", this->Name, "_TRANSITIVE_DEPENDENCY");
1785 this->Makefile->GetState()->SetGlobalProperty(transitivePropName, "False");
1787 std::string const found = cmStrCat(this->Name, "_FOUND");
1788 std::string const upperFound = cmSystemTools::UpperCase(found);
1790 bool const upperResult = this->Makefile->IsOn(upperFound);
1791 bool const result = this->Makefile->IsOn(found);
1792 bool const packageFound = (result || upperResult);
1794 this->AppendToFoundProperty(packageFound);
1796 // Record whether the find was quiet or not, so this can be used
1797 // e.g. in FeatureSummary.cmake
1798 std::string const quietInfoPropName =
1799 cmStrCat("_CMAKE_", this->Name, "_QUIET");
1800 this->Makefile->GetState()->SetGlobalProperty(
1801 quietInfoPropName, this->Quiet ? "TRUE" : "FALSE");
1803 // set a global property to record the required version of this package
1804 std::string const versionInfoPropName =
1805 cmStrCat("_CMAKE_", this->Name, "_REQUIRED_VERSION");
1806 std::string versionInfo;
1807 if (!this->VersionRange.empty()) {
1808 versionInfo = this->VersionRange;
1809 } else if (!this->Version.empty()) {
1811 cmStrCat(this->VersionExact ? "==" : ">=", ' ', this->Version);
1813 this->Makefile->GetState()->SetGlobalProperty(versionInfoPropName,
1814 versionInfo.c_str());
1815 if (this->Required) {
1816 std::string const requiredInfoPropName =
1817 cmStrCat("_CMAKE_", this->Name, "_TYPE");
1818 this->Makefile->GetState()->SetGlobalProperty(requiredInfoPropName,
1823 void cmFindPackageCommand::ComputePrefixes()
1825 this->FillPrefixesPackageRedirect();
1827 if (!this->NoDefaultPath) {
1828 if (!this->NoPackageRootPath) {
1829 this->FillPrefixesPackageRoot();
1831 if (!this->NoCMakePath) {
1832 this->FillPrefixesCMakeVariable();
1834 if (!this->NoCMakeEnvironmentPath) {
1835 this->FillPrefixesCMakeEnvironment();
1839 this->FillPrefixesUserHints();
1841 if (!this->NoDefaultPath) {
1842 if (!this->NoSystemEnvironmentPath) {
1843 this->FillPrefixesSystemEnvironment();
1845 if (!this->NoUserRegistry) {
1846 this->FillPrefixesUserRegistry();
1848 if (!this->NoCMakeSystemPath) {
1849 this->FillPrefixesCMakeSystemVariable();
1851 if (!this->NoSystemRegistry) {
1852 this->FillPrefixesSystemRegistry();
1855 this->FillPrefixesUserGuess();
1857 this->ComputeFinalPaths(IgnorePaths::No);
1860 void cmFindPackageCommand::FillPrefixesPackageRedirect()
1862 cmSearchPath& paths = this->LabeledPaths[PathLabel::PackageRedirect];
1864 const auto redirectDir =
1865 this->Makefile->GetDefinition("CMAKE_FIND_PACKAGE_REDIRECTS_DIR");
1866 if (redirectDir && !redirectDir->empty()) {
1867 paths.AddPath(*redirectDir);
1869 if (this->DebugMode) {
1870 std::string debugBuffer =
1871 "The internally managed CMAKE_FIND_PACKAGE_REDIRECTS_DIR.\n";
1872 collectPathsForDebug(debugBuffer, paths);
1873 this->DebugBuffer = cmStrCat(this->DebugBuffer, debugBuffer);
1877 void cmFindPackageCommand::FillPrefixesPackageRoot()
1879 cmSearchPath& paths = this->LabeledPaths[PathLabel::PackageRoot];
1881 // Add the PACKAGE_ROOT_PATH from each enclosing find_package call.
1882 for (auto pkgPaths = this->Makefile->FindPackageRootPathStack.rbegin();
1883 pkgPaths != this->Makefile->FindPackageRootPathStack.rend();
1885 for (std::string const& path : *pkgPaths) {
1886 paths.AddPath(path);
1889 if (this->DebugMode) {
1890 std::string debugBuffer = "<PackageName>_ROOT CMake variable "
1891 "[CMAKE_FIND_USE_PACKAGE_ROOT_PATH].\n";
1892 collectPathsForDebug(debugBuffer, paths);
1893 this->DebugBuffer = cmStrCat(this->DebugBuffer, debugBuffer);
1897 void cmFindPackageCommand::FillPrefixesCMakeEnvironment()
1899 cmSearchPath& paths = this->LabeledPaths[PathLabel::CMakeEnvironment];
1900 std::string debugBuffer;
1901 std::size_t debugOffset = 0;
1903 // Check the environment variable with the same name as the cache
1905 paths.AddEnvPath(this->Variable);
1906 if (this->DebugMode) {
1907 debugBuffer = cmStrCat("Env variable ", this->Variable,
1908 " [CMAKE_FIND_USE_CMAKE_ENVIRONMENT_PATH].\n");
1909 debugOffset = collectPathsForDebug(debugBuffer, paths);
1912 // And now the general CMake environment variables
1913 paths.AddEnvPath("CMAKE_PREFIX_PATH");
1914 if (this->DebugMode) {
1915 debugBuffer = cmStrCat(debugBuffer,
1916 "CMAKE_PREFIX_PATH env variable "
1917 "[CMAKE_FIND_USE_CMAKE_ENVIRONMENT_PATH].\n");
1918 debugOffset = collectPathsForDebug(debugBuffer, paths, debugOffset);
1921 paths.AddEnvPath("CMAKE_FRAMEWORK_PATH");
1922 paths.AddEnvPath("CMAKE_APPBUNDLE_PATH");
1923 if (this->DebugMode) {
1925 cmStrCat(debugBuffer,
1926 "CMAKE_FRAMEWORK_PATH and CMAKE_APPBUNDLE_PATH env "
1927 "variables [CMAKE_FIND_USE_CMAKE_ENVIRONMENT_PATH].\n");
1928 collectPathsForDebug(debugBuffer, paths, debugOffset);
1929 this->DebugBuffer = cmStrCat(this->DebugBuffer, debugBuffer);
1933 void cmFindPackageCommand::FillPrefixesCMakeVariable()
1935 cmSearchPath& paths = this->LabeledPaths[PathLabel::CMake];
1936 std::string debugBuffer;
1937 std::size_t debugOffset = 0;
1939 paths.AddCMakePath("CMAKE_PREFIX_PATH");
1940 if (this->DebugMode) {
1941 debugBuffer = "CMAKE_PREFIX_PATH variable [CMAKE_FIND_USE_CMAKE_PATH].\n";
1942 debugOffset = collectPathsForDebug(debugBuffer, paths);
1945 paths.AddCMakePath("CMAKE_FRAMEWORK_PATH");
1946 paths.AddCMakePath("CMAKE_APPBUNDLE_PATH");
1947 if (this->DebugMode) {
1949 cmStrCat(debugBuffer,
1950 "CMAKE_FRAMEWORK_PATH and CMAKE_APPBUNDLE_PATH variables "
1951 "[CMAKE_FIND_USE_CMAKE_PATH].\n");
1952 collectPathsForDebug(debugBuffer, paths, debugOffset);
1953 this->DebugBuffer = cmStrCat(this->DebugBuffer, debugBuffer);
1957 void cmFindPackageCommand::FillPrefixesSystemEnvironment()
1959 cmSearchPath& paths = this->LabeledPaths[PathLabel::SystemEnvironment];
1961 // Use the system search path to generate prefixes.
1962 // Relative paths are interpreted with respect to the current
1963 // working directory.
1964 std::vector<std::string> tmp;
1965 cmSystemTools::GetPath(tmp);
1966 for (std::string const& i : tmp) {
1967 // If the path is a PREFIX/bin case then add its parent instead.
1968 if ((cmHasLiteralSuffix(i, "/bin")) || (cmHasLiteralSuffix(i, "/sbin"))) {
1969 paths.AddPath(cmSystemTools::GetFilenamePath(i));
1974 if (this->DebugMode) {
1975 std::string debugBuffer = "Standard system environment variables "
1976 "[CMAKE_FIND_USE_SYSTEM_ENVIRONMENT_PATH].\n";
1977 collectPathsForDebug(debugBuffer, paths);
1978 this->DebugBuffer = cmStrCat(this->DebugBuffer, debugBuffer);
1982 void cmFindPackageCommand::FillPrefixesUserRegistry()
1984 #if defined(_WIN32) && !defined(__CYGWIN__)
1985 this->LoadPackageRegistryWinUser();
1986 #elif defined(__HAIKU__)
1987 char dir[B_PATH_NAME_LENGTH];
1988 if (find_directory(B_USER_SETTINGS_DIRECTORY, -1, false, dir, sizeof(dir)) ==
1990 std::string fname = cmStrCat(dir, "/cmake/packages/", Name);
1991 this->LoadPackageRegistryDir(fname,
1992 this->LabeledPaths[PathLabel::UserRegistry]);
1996 if (cmSystemTools::GetEnv("HOME", dir)) {
1997 dir += "/.cmake/packages/";
1999 this->LoadPackageRegistryDir(dir,
2000 this->LabeledPaths[PathLabel::UserRegistry]);
2003 if (this->DebugMode) {
2004 std::string debugBuffer =
2005 "CMake User Package Registry [CMAKE_FIND_USE_PACKAGE_REGISTRY].\n";
2006 collectPathsForDebug(debugBuffer,
2007 this->LabeledPaths[PathLabel::UserRegistry]);
2008 this->DebugBuffer = cmStrCat(this->DebugBuffer, debugBuffer);
2012 void cmFindPackageCommand::FillPrefixesSystemRegistry()
2014 if (this->NoSystemRegistry || this->NoDefaultPath) {
2018 #if defined(_WIN32) && !defined(__CYGWIN__)
2019 this->LoadPackageRegistryWinSystem();
2022 if (this->DebugMode) {
2023 std::string debugBuffer =
2024 "CMake System Package Registry "
2025 "[CMAKE_FIND_PACKAGE_NO_SYSTEM_PACKAGE_REGISTRY].\n";
2026 collectPathsForDebug(debugBuffer,
2027 this->LabeledPaths[PathLabel::SystemRegistry]);
2028 this->DebugBuffer = cmStrCat(this->DebugBuffer, debugBuffer);
2032 #if defined(_WIN32) && !defined(__CYGWIN__)
2033 void cmFindPackageCommand::LoadPackageRegistryWinUser()
2035 // HKEY_CURRENT_USER\\Software shares 32-bit and 64-bit views.
2036 this->LoadPackageRegistryWin(true, 0,
2037 this->LabeledPaths[PathLabel::UserRegistry]);
2040 void cmFindPackageCommand::LoadPackageRegistryWinSystem()
2042 cmSearchPath& paths = this->LabeledPaths[PathLabel::SystemRegistry];
2044 // HKEY_LOCAL_MACHINE\\SOFTWARE has separate 32-bit and 64-bit views.
2045 // Prefer the target platform view first.
2046 if (this->Makefile->PlatformIs64Bit()) {
2047 this->LoadPackageRegistryWin(false, KEY_WOW64_64KEY, paths);
2048 this->LoadPackageRegistryWin(false, KEY_WOW64_32KEY, paths);
2050 this->LoadPackageRegistryWin(false, KEY_WOW64_32KEY, paths);
2051 this->LoadPackageRegistryWin(false, KEY_WOW64_64KEY, paths);
2055 void cmFindPackageCommand::LoadPackageRegistryWin(const bool user,
2056 const unsigned int view,
2057 cmSearchPath& outPaths)
2059 std::wstring key = L"Software\\Kitware\\CMake\\Packages\\";
2060 key += cmsys::Encoding::ToWide(this->Name);
2061 std::set<std::wstring> bad;
2063 if (RegOpenKeyExW(user ? HKEY_CURRENT_USER : HKEY_LOCAL_MACHINE, key.c_str(),
2064 0, KEY_QUERY_VALUE | view, &hKey) == ERROR_SUCCESS) {
2065 DWORD valueType = REG_NONE;
2066 wchar_t name[16383]; // RegEnumValue docs limit name to 32767 _bytes_
2067 std::vector<wchar_t> data(512);
2071 DWORD nameSize = static_cast<DWORD>(sizeof(name));
2072 DWORD dataSize = static_cast<DWORD>(data.size() * sizeof(data[0]));
2073 switch (RegEnumValueW(hKey, index, name, &nameSize, 0, &valueType,
2074 (BYTE*)&data[0], &dataSize)) {
2077 if (valueType == REG_SZ) {
2079 if (!this->CheckPackageRegistryEntry(
2080 cmsys::Encoding::ToNarrow(&data[0]), outPaths)) {
2081 // The entry is invalid.
2086 case ERROR_MORE_DATA:
2087 data.resize((dataSize + sizeof(data[0]) - 1) / sizeof(data[0]));
2089 case ERROR_NO_MORE_ITEMS:
2098 // Remove bad values if possible.
2099 if (user && !bad.empty() &&
2100 RegOpenKeyExW(HKEY_CURRENT_USER, key.c_str(), 0, KEY_SET_VALUE | view,
2101 &hKey) == ERROR_SUCCESS) {
2102 for (std::wstring const& v : bad) {
2103 RegDeleteValueW(hKey, v.c_str());
2110 void cmFindPackageCommand::LoadPackageRegistryDir(std::string const& dir,
2111 cmSearchPath& outPaths)
2113 cmsys::Directory files;
2114 if (!files.Load(dir)) {
2119 for (unsigned long i = 0; i < files.GetNumberOfFiles(); ++i) {
2120 fname = cmStrCat(dir, '/', files.GetFile(i));
2122 if (!cmSystemTools::FileIsDirectory(fname)) {
2123 // Hold this file hostage until it behaves.
2124 cmFindPackageCommandHoldFile holdFile(fname.c_str());
2127 cmsys::ifstream fin(fname.c_str(), std::ios::in | std::ios::binary);
2129 if (fin && cmSystemTools::GetLineFromStream(fin, fentry) &&
2130 this->CheckPackageRegistryEntry(fentry, outPaths)) {
2131 // The file references an existing package, so release it.
2137 // TODO: Wipe out the directory if it is empty.
2141 bool cmFindPackageCommand::CheckPackageRegistryEntry(const std::string& fname,
2142 cmSearchPath& outPaths)
2144 // Parse the content of one package registry entry.
2145 if (cmSystemTools::FileIsFullPath(fname)) {
2146 // The first line in the stream is the full path to a file or
2147 // directory containing the package.
2148 if (cmSystemTools::FileExists(fname)) {
2149 // The path exists. Look for the package here.
2150 if (!cmSystemTools::FileIsDirectory(fname)) {
2151 outPaths.AddPath(cmSystemTools::GetFilenamePath(fname));
2153 outPaths.AddPath(fname);
2157 // The path does not exist. Assume the stream content is
2158 // associated with an old package that no longer exists, and
2159 // delete it to keep the package registry clean.
2162 // The first line in the stream is not the full path to a file or
2163 // directory. Assume the stream content was created by a future
2164 // version of CMake that uses a different format, and leave it.
2168 void cmFindPackageCommand::FillPrefixesCMakeSystemVariable()
2170 cmSearchPath& paths = this->LabeledPaths[PathLabel::CMakeSystem];
2172 const bool install_prefix_in_list =
2173 !this->Makefile->IsOn("CMAKE_FIND_NO_INSTALL_PREFIX");
2174 const bool remove_install_prefix = this->NoCMakeInstallPath;
2175 const bool add_install_prefix = !this->NoCMakeInstallPath &&
2176 this->Makefile->IsDefinitionSet("CMAKE_FIND_USE_INSTALL_PREFIX");
2178 // We have 3 possible states for `CMAKE_SYSTEM_PREFIX_PATH` and
2179 // `CMAKE_INSTALL_PREFIX`.
2180 // Either we need to remove `CMAKE_INSTALL_PREFIX`, add
2181 // `CMAKE_INSTALL_PREFIX`, or do nothing.
2183 // When we need to remove `CMAKE_INSTALL_PREFIX` we remove the Nth occurrence
2184 // of `CMAKE_INSTALL_PREFIX` from `CMAKE_SYSTEM_PREFIX_PATH`, where `N` is
2185 // computed by `CMakeSystemSpecificInformation.cmake` while constructing
2186 // `CMAKE_SYSTEM_PREFIX_PATH`. This ensures that if projects / toolchains
2187 // have removed `CMAKE_INSTALL_PREFIX` from the list, we don't remove
2188 // some other entry by mistake
2189 long install_prefix_count = -1;
2190 std::string install_path_to_remove;
2191 if (cmValue to_skip = this->Makefile->GetDefinition(
2192 "_CMAKE_SYSTEM_PREFIX_PATH_INSTALL_PREFIX_COUNT")) {
2193 cmStrToLong(to_skip, &install_prefix_count);
2195 if (cmValue install_value = this->Makefile->GetDefinition(
2196 "_CMAKE_SYSTEM_PREFIX_PATH_INSTALL_PREFIX_VALUE")) {
2197 install_path_to_remove = *install_value;
2200 if (remove_install_prefix && install_prefix_in_list &&
2201 install_prefix_count > 0 && !install_path_to_remove.empty()) {
2203 cmValue prefix_paths =
2204 this->Makefile->GetDefinition("CMAKE_SYSTEM_PREFIX_PATH");
2205 // remove entry from CMAKE_SYSTEM_PREFIX_PATH
2206 std::vector<std::string> expanded = cmExpandedList(*prefix_paths);
2208 for (const auto& path : expanded) {
2210 !(path == install_path_to_remove && ++count == install_prefix_count);
2212 paths.AddPath(path);
2215 } else if (add_install_prefix && !install_prefix_in_list) {
2216 paths.AddCMakePath("CMAKE_INSTALL_PREFIX");
2217 paths.AddCMakePath("CMAKE_SYSTEM_PREFIX_PATH");
2219 // Otherwise the current setup of `CMAKE_SYSTEM_PREFIX_PATH` is correct
2220 paths.AddCMakePath("CMAKE_SYSTEM_PREFIX_PATH");
2223 paths.AddCMakePath("CMAKE_SYSTEM_FRAMEWORK_PATH");
2224 paths.AddCMakePath("CMAKE_SYSTEM_APPBUNDLE_PATH");
2226 if (this->DebugMode) {
2227 std::string debugBuffer = "CMake variables defined in the Platform file "
2228 "[CMAKE_FIND_USE_CMAKE_SYSTEM_PATH].\n";
2229 collectPathsForDebug(debugBuffer, paths);
2230 this->DebugBuffer = cmStrCat(this->DebugBuffer, debugBuffer);
2234 void cmFindPackageCommand::FillPrefixesUserGuess()
2236 cmSearchPath& paths = this->LabeledPaths[PathLabel::Guess];
2238 for (std::string const& p : this->UserGuessArgs) {
2239 paths.AddUserPath(p);
2241 if (this->DebugMode) {
2242 std::string debugBuffer =
2243 "Paths specified by the find_package PATHS option.\n";
2244 collectPathsForDebug(debugBuffer, paths);
2245 this->DebugBuffer = cmStrCat(this->DebugBuffer, debugBuffer);
2249 void cmFindPackageCommand::FillPrefixesUserHints()
2251 cmSearchPath& paths = this->LabeledPaths[PathLabel::Hints];
2253 for (std::string const& p : this->UserHintsArgs) {
2254 paths.AddUserPath(p);
2256 if (this->DebugMode) {
2257 std::string debugBuffer =
2258 "Paths specified by the find_package HINTS option.\n";
2259 collectPathsForDebug(debugBuffer, paths);
2260 this->DebugBuffer = cmStrCat(this->DebugBuffer, debugBuffer);
2264 bool cmFindPackageCommand::SearchDirectory(std::string const& dir)
2266 assert(!dir.empty() && dir.back() == '/');
2268 // Check each path suffix on this directory.
2269 for (std::string const& s : this->SearchPathSuffixes) {
2270 std::string d = dir;
2275 if (this->CheckDirectory(d)) {
2282 bool cmFindPackageCommand::CheckDirectory(std::string const& dir)
2284 assert(!dir.empty() && dir.back() == '/');
2286 // Look for the file in this directory.
2287 std::string const d = dir.substr(0, dir.size() - 1);
2288 if (this->FindConfigFile(d, this->FileFound)) {
2289 // Remove duplicate slashes.
2290 cmSystemTools::ConvertToUnixSlashes(this->FileFound);
2296 bool cmFindPackageCommand::FindConfigFile(std::string const& dir,
2299 if (this->IgnoredPaths.count(dir)) {
2303 for (std::string const& c : this->Configs) {
2304 file = cmStrCat(dir, '/', c);
2305 if (this->DebugMode) {
2306 this->DebugBuffer = cmStrCat(this->DebugBuffer, " ", file, "\n");
2308 if (cmSystemTools::FileExists(file, true) && this->CheckVersion(file)) {
2309 // Allow resolving symlinks when the config file is found through a link
2310 if (this->UseRealPath) {
2311 file = cmSystemTools::GetRealPath(file);
2319 bool cmFindPackageCommand::CheckVersion(std::string const& config_file)
2321 bool result = false; // by default, assume the version is not ok.
2322 bool haveResult = false;
2323 std::string version = "unknown";
2325 // Get the filename without the .cmake extension.
2326 std::string::size_type pos = config_file.rfind('.');
2327 std::string version_file_base = config_file.substr(0, pos);
2329 // Look for foo-config-version.cmake
2330 std::string version_file = cmStrCat(version_file_base, "-version.cmake");
2331 if (!haveResult && cmSystemTools::FileExists(version_file, true)) {
2332 result = this->CheckVersionFile(version_file, version);
2336 // Look for fooConfigVersion.cmake
2337 version_file = cmStrCat(version_file_base, "Version.cmake");
2338 if (!haveResult && cmSystemTools::FileExists(version_file, true)) {
2339 result = this->CheckVersionFile(version_file, version);
2343 // If no version was requested a versionless package is acceptable.
2344 if (!haveResult && this->Version.empty()) {
2348 ConfigFileInfo configFileInfo;
2349 configFileInfo.filename = config_file;
2350 configFileInfo.version = version;
2351 this->ConsideredConfigs.push_back(std::move(configFileInfo));
2356 bool cmFindPackageCommand::CheckVersionFile(std::string const& version_file,
2357 std::string& result_version)
2359 // The version file will be loaded in an isolated scope.
2360 cmMakefile::ScopePushPop const varScope(this->Makefile);
2361 cmMakefile::PolicyPushPop const polScope(this->Makefile);
2362 static_cast<void>(varScope);
2363 static_cast<void>(polScope);
2365 // Clear the output variables.
2366 this->Makefile->RemoveDefinition("PACKAGE_VERSION");
2367 this->Makefile->RemoveDefinition("PACKAGE_VERSION_UNSUITABLE");
2368 this->Makefile->RemoveDefinition("PACKAGE_VERSION_COMPATIBLE");
2369 this->Makefile->RemoveDefinition("PACKAGE_VERSION_EXACT");
2371 // Set the input variables.
2372 this->Makefile->AddDefinition("PACKAGE_FIND_NAME", this->Name);
2373 this->Makefile->AddDefinition("PACKAGE_FIND_VERSION_COMPLETE",
2374 this->VersionComplete);
2376 auto addDefinition = [this](const std::string& variable,
2377 cm::string_view value) {
2378 this->Makefile->AddDefinition(variable, value);
2380 this->SetVersionVariables(addDefinition, "PACKAGE_FIND_VERSION",
2381 this->Version, this->VersionCount,
2382 this->VersionMajor, this->VersionMinor,
2383 this->VersionPatch, this->VersionTweak);
2384 if (!this->VersionRange.empty()) {
2385 this->SetVersionVariables(addDefinition, "PACKAGE_FIND_VERSION_MIN",
2386 this->Version, this->VersionCount,
2387 this->VersionMajor, this->VersionMinor,
2388 this->VersionPatch, this->VersionTweak);
2389 this->SetVersionVariables(addDefinition, "PACKAGE_FIND_VERSION_MAX",
2390 this->VersionMax, this->VersionMaxCount,
2391 this->VersionMaxMajor, this->VersionMaxMinor,
2392 this->VersionMaxPatch, this->VersionMaxTweak);
2394 this->Makefile->AddDefinition("PACKAGE_FIND_VERSION_RANGE",
2395 this->VersionComplete);
2396 this->Makefile->AddDefinition("PACKAGE_FIND_VERSION_RANGE_MIN",
2397 this->VersionRangeMin);
2398 this->Makefile->AddDefinition("PACKAGE_FIND_VERSION_RANGE_MAX",
2399 this->VersionRangeMax);
2402 // Load the version check file. Pass NoPolicyScope because we do
2403 // our own policy push/pop independent of CMP0011.
2404 bool suitable = false;
2405 if (this->ReadListFile(version_file, NoPolicyScope)) {
2406 // Check the output variables.
2407 bool okay = this->Makefile->IsOn("PACKAGE_VERSION_EXACT");
2408 bool const unsuitable = this->Makefile->IsOn("PACKAGE_VERSION_UNSUITABLE");
2409 if (!okay && !this->VersionExact) {
2410 okay = this->Makefile->IsOn("PACKAGE_VERSION_COMPATIBLE");
2413 // The package is suitable if the version is okay and not
2414 // explicitly unsuitable.
2415 suitable = !unsuitable && (okay || this->Version.empty());
2417 // Get the version found.
2418 this->VersionFound =
2419 this->Makefile->GetSafeDefinition("PACKAGE_VERSION");
2421 // Try to parse the version number and store the results that were
2422 // successfully parsed.
2423 unsigned int parsed_major;
2424 unsigned int parsed_minor;
2425 unsigned int parsed_patch;
2426 unsigned int parsed_tweak;
2427 this->VersionFoundCount =
2428 parseVersion(this->VersionFound, parsed_major, parsed_minor,
2429 parsed_patch, parsed_tweak);
2430 switch (this->VersionFoundCount) {
2432 this->VersionFoundTweak = parsed_tweak;
2435 this->VersionFoundPatch = parsed_patch;
2438 this->VersionFoundMinor = parsed_minor;
2441 this->VersionFoundMajor = parsed_major;
2449 result_version = this->Makefile->GetSafeDefinition("PACKAGE_VERSION");
2450 if (result_version.empty()) {
2451 result_version = "unknown";
2454 // Succeed if the version is suitable.
2458 void cmFindPackageCommand::StoreVersionFound()
2460 // Store the whole version string.
2461 std::string const ver = cmStrCat(this->Name, "_VERSION");
2462 auto addDefinition = [this](const std::string& variable,
2463 cm::string_view value) {
2464 this->Makefile->AddDefinition(variable, value);
2467 this->SetVersionVariables(addDefinition, ver, this->VersionFound,
2468 this->VersionFoundCount, this->VersionFoundMajor,
2469 this->VersionFoundMinor, this->VersionFoundPatch,
2470 this->VersionFoundTweak);
2472 if (this->VersionFound.empty()) {
2473 this->Makefile->RemoveDefinition(ver);
2477 bool cmFindPackageCommand::SearchPrefix(std::string const& prefix_in)
2479 assert(!prefix_in.empty() && prefix_in.back() == '/');
2481 // Skip this if the prefix does not exist.
2482 if (!cmSystemTools::FileIsDirectory(prefix_in)) {
2486 // Skip this if it's in ignored paths.
2487 std::string prefixWithoutSlash = prefix_in;
2488 if (prefixWithoutSlash != "/" && prefixWithoutSlash.back() == '/') {
2489 prefixWithoutSlash.erase(prefixWithoutSlash.length() - 1);
2491 if (this->IgnoredPaths.count(prefixWithoutSlash) ||
2492 this->IgnoredPrefixPaths.count(prefixWithoutSlash)) {
2496 // PREFIX/ (useful on windows or in build trees)
2497 if (this->SearchDirectory(prefix_in)) {
2501 // Strip the trailing slash because the path generator is about to
2503 std::string const prefix = prefix_in.substr(0, prefix_in.size() - 1);
2505 auto searchFn = [this](const std::string& fullPath) -> bool {
2506 return this->SearchDirectory(fullPath);
2509 auto iCMakeGen = cmCaseInsensitiveDirectoryListGenerator{ "cmake"_s };
2510 auto firstPkgDirGen =
2511 cmProjectDirectoryListGenerator{ this->Names, this->SortOrder,
2512 this->SortDirection };
2514 // PREFIX/(cmake|CMake)/ (useful on windows or in build trees)
2515 if (TryGeneratedPaths(searchFn, prefix, iCMakeGen)) {
2519 // PREFIX/(Foo|foo|FOO).*/
2520 if (TryGeneratedPaths(searchFn, prefix, firstPkgDirGen)) {
2524 // PREFIX/(Foo|foo|FOO).*/(cmake|CMake)/
2525 if (TryGeneratedPaths(searchFn, prefix, firstPkgDirGen, iCMakeGen)) {
2529 auto secondPkgDirGen =
2530 cmProjectDirectoryListGenerator{ this->Names, this->SortOrder,
2531 this->SortDirection };
2533 // PREFIX/(Foo|foo|FOO).*/(cmake|CMake)/(Foo|foo|FOO).*/
2534 if (TryGeneratedPaths(searchFn, prefix, firstPkgDirGen, iCMakeGen,
2539 // Construct list of common install locations (lib and share).
2540 std::vector<cm::string_view> common;
2541 std::string libArch;
2542 if (!this->LibraryArchitecture.empty()) {
2543 libArch = "lib/" + this->LibraryArchitecture;
2544 common.emplace_back(libArch);
2546 if (this->UseLib32Paths) {
2547 common.emplace_back("lib32"_s);
2549 if (this->UseLib64Paths) {
2550 common.emplace_back("lib64"_s);
2552 if (this->UseLibx32Paths) {
2553 common.emplace_back("libx32"_s);
2555 common.emplace_back("lib"_s);
2556 common.emplace_back("share"_s);
2558 auto cmnGen = cmEnumPathSegmentsGenerator{ common };
2559 auto cmakeGen = cmAppendPathSegmentGenerator{ "cmake"_s };
2561 // PREFIX/(lib/ARCH|lib*|share)/cmake/(Foo|foo|FOO).*/
2562 if (TryGeneratedPaths(searchFn, prefix, cmnGen, cmakeGen, firstPkgDirGen)) {
2566 // PREFIX/(lib/ARCH|lib*|share)/(Foo|foo|FOO).*/
2567 if (TryGeneratedPaths(searchFn, prefix, cmnGen, firstPkgDirGen)) {
2571 // PREFIX/(lib/ARCH|lib*|share)/(Foo|foo|FOO).*/(cmake|CMake)/
2572 if (TryGeneratedPaths(searchFn, prefix, cmnGen, firstPkgDirGen, iCMakeGen)) {
2576 // PREFIX/(Foo|foo|FOO).*/(lib/ARCH|lib*|share)/cmake/(Foo|foo|FOO).*/
2577 if (TryGeneratedPaths(searchFn, prefix, firstPkgDirGen, cmnGen, cmakeGen,
2582 // PREFIX/(Foo|foo|FOO).*/(lib/ARCH|lib*|share)/(Foo|foo|FOO).*/
2583 if (TryGeneratedPaths(searchFn, prefix, firstPkgDirGen, cmnGen,
2588 // PREFIX/(Foo|foo|FOO).*/(lib/ARCH|lib*|share)/(Foo|foo|FOO).*/(cmake|CMake)/
2589 return TryGeneratedPaths(searchFn, prefix, firstPkgDirGen, cmnGen,
2590 secondPkgDirGen, iCMakeGen);
2593 bool cmFindPackageCommand::SearchFrameworkPrefix(std::string const& prefix_in)
2595 assert(!prefix_in.empty() && prefix_in.back() == '/');
2597 // Strip the trailing slash because the path generator is about to
2599 std::string const prefix = prefix_in.substr(0, prefix_in.size() - 1);
2601 auto searchFn = [this](const std::string& fullPath) -> bool {
2602 return this->SearchDirectory(fullPath);
2605 auto iCMakeGen = cmCaseInsensitiveDirectoryListGenerator{ "cmake"_s };
2607 cmMacProjectDirectoryListGenerator{ this->Names, ".framework"_s };
2608 auto rGen = cmAppendPathSegmentGenerator{ "Resources"_s };
2609 auto vGen = cmAppendPathSegmentGenerator{ "Versions"_s };
2610 auto grGen = cmFileListGeneratorGlob{ "/*/Resources"_s };
2612 // <prefix>/Foo.framework/Resources/
2613 if (TryGeneratedPaths(searchFn, prefix, fwGen, rGen)) {
2617 // <prefix>/Foo.framework/Resources/CMake/
2618 if (TryGeneratedPaths(searchFn, prefix, fwGen, rGen, iCMakeGen)) {
2622 // <prefix>/Foo.framework/Versions/*/Resources/
2623 if (TryGeneratedPaths(searchFn, prefix, fwGen, vGen, grGen)) {
2627 // <prefix>/Foo.framework/Versions/*/Resources/CMake/
2628 return TryGeneratedPaths(searchFn, prefix, fwGen, vGen, grGen, iCMakeGen);
2631 bool cmFindPackageCommand::SearchAppBundlePrefix(std::string const& prefix_in)
2633 assert(!prefix_in.empty() && prefix_in.back() == '/');
2635 // Strip the trailing slash because the path generator is about to
2637 std::string const prefix = prefix_in.substr(0, prefix_in.size() - 1);
2639 auto searchFn = [this](const std::string& fullPath) -> bool {
2640 return this->SearchDirectory(fullPath);
2643 auto appGen = cmMacProjectDirectoryListGenerator{ this->Names, ".app"_s };
2644 auto crGen = cmAppendPathSegmentGenerator{ "Contents/Resources"_s };
2646 // <prefix>/Foo.app/Contents/Resources
2647 if (TryGeneratedPaths(searchFn, prefix, appGen, crGen)) {
2651 // <prefix>/Foo.app/Contents/Resources/CMake
2652 return TryGeneratedPaths(
2653 searchFn, prefix, appGen, crGen,
2654 cmCaseInsensitiveDirectoryListGenerator{ "cmake"_s });
2657 // TODO: Debug cmsys::Glob double slash problem.
2659 bool cmFindPackage(std::vector<std::string> const& args,
2660 cmExecutionStatus& status)
2662 return cmFindPackageCommand(status).InitialPass(args);