resolve cyclic dependency with zstd
[platform/upstream/cmake.git] / Source / cmFindPackageCommand.cxx
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"
4
5 #include <algorithm>
6 #include <cassert>
7 #include <cstdio>
8 #include <deque>
9 #include <functional>
10 #include <iterator>
11 #include <sstream>
12 #include <utility>
13
14 #include <cm/memory>
15 #include <cm/optional>
16 #include <cmext/string_view>
17
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"
23
24 #include "cmAlgorithms.h"
25 #include "cmDependencyProvider.h"
26 #include "cmListFileCache.h"
27 #include "cmMakefile.h"
28 #include "cmMessageType.h"
29 #include "cmPolicies.h"
30 #include "cmRange.h"
31 #include "cmSearchPath.h"
32 #include "cmState.h"
33 #include "cmStateTypes.h"
34 #include "cmStringAlgorithms.h"
35 #include "cmSystemTools.h"
36 #include "cmValue.h"
37 #include "cmVersion.h"
38 #include "cmWindowsRegistry.h"
39
40 #if defined(__HAIKU__)
41 #  include <FindDirectory.h>
42 #  include <StorageDefs.h>
43 #endif
44
45 #if defined(_WIN32) && !defined(__CYGWIN__)
46 #  include <windows.h>
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
50 #  endif
51 #  if !defined(KEY_WOW64_64KEY)
52 #    define KEY_WOW64_64KEY 0x0100
53 #  endif
54 #endif
55
56 class cmExecutionStatus;
57
58 namespace {
59
60 template <template <typename> class Op>
61 struct StrverscmpOp
62 {
63   bool operator()(const std::string& lhs, const std::string& rhs) const
64   {
65     return Op<int>()(cmSystemTools::strverscmp(lhs, rhs), 0);
66   }
67 };
68
69 std::size_t collectPathsForDebug(std::string& buffer,
70                                  cmSearchPath const& searchPath,
71                                  std::size_t const startIndex = 0)
72 {
73   const auto& paths = searchPath.GetPaths();
74   if (paths.empty()) {
75     buffer += "  none\n";
76     return 0;
77   }
78   for (auto i = startIndex; i < paths.size(); i++) {
79     buffer += "  " + paths[i].Path + "\n";
80   }
81   return paths.size();
82 }
83
84 #if !(defined(_WIN32) && !defined(__CYGWIN__))
85 class cmFindPackageCommandHoldFile
86 {
87   const char* File;
88
89 public:
90   cmFindPackageCommandHoldFile(const char* const f)
91     : File(f)
92   {
93   }
94   ~cmFindPackageCommandHoldFile()
95   {
96     if (this->File) {
97       cmSystemTools::RemoveFile(this->File);
98     }
99   }
100   cmFindPackageCommandHoldFile(const cmFindPackageCommandHoldFile&) = delete;
101   cmFindPackageCommandHoldFile& operator=(
102     const cmFindPackageCommandHoldFile&) = delete;
103   void Release() { this->File = nullptr; }
104 };
105 #endif
106
107 bool isDirentryToIgnore(const char* const fname)
108 {
109   assert(fname != nullptr);
110   assert(fname[0] != 0);
111   return fname[0] == '.' &&
112     (fname[1] == 0 || (fname[1] == '.' && fname[2] == 0));
113 }
114
115 class cmAppendPathSegmentGenerator
116 {
117 public:
118   cmAppendPathSegmentGenerator(cm::string_view dirName)
119     : DirName{ dirName }
120   {
121   }
122
123   std::string GetNextCandidate(const std::string& parent)
124   {
125     if (this->NeedReset) {
126       return {};
127     }
128     this->NeedReset = true;
129     return cmStrCat(parent, '/', this->DirName);
130   }
131
132   void Reset() { this->NeedReset = false; }
133
134 private:
135   const cm::string_view DirName;
136   bool NeedReset = false;
137 };
138
139 class cmEnumPathSegmentsGenerator
140 {
141 public:
142   cmEnumPathSegmentsGenerator(const std::vector<cm::string_view>& init)
143     : Names{ init }
144     , Current{ this->Names.get().cbegin() }
145   {
146   }
147
148   std::string GetNextCandidate(const std::string& parent)
149   {
150     if (this->Current != this->Names.get().cend()) {
151       return cmStrCat(parent, '/', *this->Current++);
152     }
153     return {};
154   }
155
156   void Reset() { this->Current = this->Names.get().cbegin(); }
157
158 private:
159   std::reference_wrapper<const std::vector<cm::string_view>> Names;
160   std::vector<cm::string_view>::const_iterator Current;
161 };
162
163 class cmCaseInsensitiveDirectoryListGenerator
164 {
165 public:
166   cmCaseInsensitiveDirectoryListGenerator(cm::string_view name)
167     : DirectoryLister{}
168     , DirName{ name }
169   {
170   }
171
172   std::string GetNextCandidate(const std::string& parent)
173   {
174     if (!this->Loaded) {
175       this->CurrentIdx = 0ul;
176       this->Loaded = true;
177       if (!this->DirectoryLister.Load(parent)) {
178         return {};
179       }
180     }
181
182     while (this->CurrentIdx < this->DirectoryLister.GetNumberOfFiles()) {
183       const char* const fname =
184         this->DirectoryLister.GetFile(this->CurrentIdx++);
185       if (isDirentryToIgnore(fname)) {
186         continue;
187       }
188       if (cmsysString_strcasecmp(fname, this->DirName.data()) == 0) {
189         auto candidate = cmStrCat(parent, '/', fname);
190         if (cmSystemTools::FileIsDirectory(candidate)) {
191           return candidate;
192         }
193       }
194     }
195     return {};
196   }
197
198   void Reset() { this->Loaded = false; }
199
200 private:
201   cmsys::Directory DirectoryLister;
202   const cm::string_view DirName;
203   unsigned long CurrentIdx = 0ul;
204   bool Loaded = false;
205 };
206
207 class cmDirectoryListGenerator
208 {
209 public:
210   cmDirectoryListGenerator(std::vector<std::string> const& names)
211     : Names{ names }
212     , Matches{}
213     , Current{ this->Matches.cbegin() }
214   {
215   }
216   virtual ~cmDirectoryListGenerator() = default;
217
218   std::string GetNextCandidate(const std::string& parent)
219   {
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);
229
230       // ATTENTION Is it guaranteed that first two entries are
231       // `.` and `..`?
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)) {
237           continue;
238         }
239
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
245           // to a directory!
246           const auto equal =
247             (cmsysString_strncasecmp(fname, name.c_str(), name.length()) == 0);
248           if (equal && directoryLister.FileIsDirectory(i)) {
249             this->Matches.emplace_back(fname);
250           }
251         }
252       }
253       // NOTE Customization point for `cmProjectDirectoryListGenerator`
254       this->OnMatchesLoaded();
255
256       this->Current = this->Matches.cbegin();
257     }
258
259     if (this->Current != this->Matches.cend()) {
260       auto candidate = cmStrCat(parent, '/', *this->Current++);
261       return candidate;
262     }
263
264     return {};
265   }
266
267   void Reset()
268   {
269     this->Matches.clear();
270     this->Current = this->Matches.cbegin();
271   }
272
273 protected:
274   virtual void OnMatchesLoaded() {}
275   virtual std::string TransformNameBeforeCmp(std::string same) { return same; }
276
277   std::reference_wrapper<const std::vector<std::string>> Names;
278   std::vector<std::string> Matches;
279   std::vector<std::string>::const_iterator Current;
280 };
281
282 class cmProjectDirectoryListGenerator : public cmDirectoryListGenerator
283 {
284 public:
285   cmProjectDirectoryListGenerator(std::vector<std::string> const& names,
286                                   cmFindPackageCommand::SortOrderType so,
287                                   cmFindPackageCommand::SortDirectionType sd)
288     : cmDirectoryListGenerator{ names }
289     , SortOrder{ so }
290     , SortDirection{ sd }
291   {
292   }
293
294 protected:
295   void OnMatchesLoaded() override
296   {
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);
301     }
302   }
303
304 private:
305   // sort parameters
306   const cmFindPackageCommand::SortOrderType SortOrder;
307   const cmFindPackageCommand::SortDirectionType SortDirection;
308 };
309
310 class cmMacProjectDirectoryListGenerator : public cmDirectoryListGenerator
311 {
312 public:
313   cmMacProjectDirectoryListGenerator(const std::vector<std::string>& names,
314                                      cm::string_view ext)
315     : cmDirectoryListGenerator{ names }
316     , Extension{ ext }
317   {
318   }
319
320 protected:
321   std::string TransformNameBeforeCmp(std::string name) override
322   {
323     return cmStrCat(name, this->Extension);
324   }
325
326 private:
327   const cm::string_view Extension;
328 };
329
330 class cmFileListGeneratorGlob
331 {
332 public:
333   cmFileListGeneratorGlob(cm::string_view pattern)
334     : Pattern(pattern)
335     , Files{}
336     , Current{}
337   {
338   }
339
340   std::string GetNextCandidate(const std::string& parent)
341   {
342     if (this->Files.empty()) {
343       // Glob the set of matching files.
344       std::string expr = cmStrCat(parent, this->Pattern);
345       cmsys::Glob g;
346       if (!g.FindFiles(expr)) {
347         return {};
348       }
349       this->Files = g.GetFiles();
350       this->Current = this->Files.cbegin();
351     }
352
353     // Skip non-directories
354     for (; this->Current != this->Files.cend() &&
355          !cmSystemTools::FileIsDirectory(*this->Current);
356          ++this->Current) {
357     }
358
359     return (this->Current != this->Files.cend()) ? *this->Current++
360                                                  : std::string{};
361   }
362
363   void Reset()
364   {
365     this->Files.clear();
366     this->Current = this->Files.cbegin();
367   }
368
369 private:
370   cm::string_view Pattern;
371   std::vector<std::string> Files;
372   std::vector<std::string>::const_iterator Current;
373 };
374
375 #if defined(__LCC__)
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
380 #endif
381
382 void ResetGenerator()
383 {
384 }
385
386 template <typename Generator>
387 void ResetGenerator(Generator&& generator)
388 {
389   std::forward<Generator&&>(generator).Reset();
390 }
391
392 template <typename Generator, typename... Generators>
393 void ResetGenerator(Generator&& generator, Generators&&... generators)
394 {
395   ResetGenerator(std::forward<Generator&&>(generator));
396   ResetGenerator(std::forward<Generators&&>(generators)...);
397 }
398
399 template <typename CallbackFn>
400 bool TryGeneratedPaths(CallbackFn&& filesCollector,
401                        const std::string& fullPath)
402 {
403   assert(!fullPath.empty() && fullPath.back() != '/');
404   return std::forward<CallbackFn&&>(filesCollector)(fullPath + '/');
405 }
406
407 template <typename CallbackFn, typename Generator, typename... Rest>
408 bool TryGeneratedPaths(CallbackFn&& filesCollector,
409                        const std::string& startPath, Generator&& gen,
410                        Rest&&... tail)
411 {
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)...)) {
418       return true;
419     }
420   }
421   return false;
422 }
423
424 #ifdef CM_LCC_DIAG_SUPPRESS_3288
425 #  undef CM_LCC_DIAG_SUPPRESS_3288
426 #  pragma diag_default 3288
427 #endif
428
429 #ifdef CM_LCC_DIAG_SUPPRESS_1222
430 #  undef CM_LCC_DIAG_SUPPRESS_1222
431 #  pragma diag_default 1222
432 #endif
433
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)
438 {
439   return std::sscanf(version.c_str(), "%u.%u.%u.%u", &major, &minor, &patch,
440                      &tweak);
441 }
442
443 } // anonymous namespace
444
445 cmFindPackageCommand::PathLabel
446   cmFindPackageCommand::PathLabel::PackageRedirect("PACKAGE_REDIRECT");
447 cmFindPackageCommand::PathLabel cmFindPackageCommand::PathLabel::UserRegistry(
448   "PACKAGE_REGISTRY");
449 cmFindPackageCommand::PathLabel cmFindPackageCommand::PathLabel::Builds(
450   "BUILDS");
451 cmFindPackageCommand::PathLabel
452   cmFindPackageCommand::PathLabel::SystemRegistry("SYSTEM_PACKAGE_REGISTRY");
453
454 const cm::string_view cmFindPackageCommand::VERSION_ENDPOINT_INCLUDED(
455   "INCLUDE");
456 const cm::string_view cmFindPackageCommand::VERSION_ENDPOINT_EXCLUDED(
457   "EXCLUDE");
458
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)
463 {
464   if (order == Name_order) {
465     if (dir == Dec) {
466       std::sort(begin, end, std::greater<std::string>());
467     } else {
468       std::sort(begin, end);
469     }
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
473     if (dir == Dec) {
474       std::sort(begin, end, StrverscmpOp<std::greater>());
475     } else {
476       std::sort(begin, end, StrverscmpOp<std::less>());
477     }
478   }
479   // else do not sort
480 }
481
482 cmFindPackageCommand::cmFindPackageCommand(cmExecutionStatus& status)
483   : cmFindCommon(status)
484   , VersionRangeMin(VERSION_ENDPOINT_INCLUDED)
485   , VersionRangeMax(VERSION_ENDPOINT_INCLUDED)
486 {
487   this->CMakePathName = "PACKAGE";
488   this->DebugMode = false;
489   this->AppendSearchPathGroups();
490
491   this->DeprecatedFindModules["Qt"] = cmPolicies::CMP0084;
492 }
493
494 void cmFindPackageCommand::AppendSearchPathGroups()
495 {
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);
501   labels->insert(
502     std::find(labels->begin(), labels->end(), PathLabel::CMakeSystem),
503     PathLabel::UserRegistry);
504   labels->insert(
505     std::find(labels->begin(), labels->end(), PathLabel::CMakeSystem),
506     PathLabel::Builds);
507   labels->insert(std::find(labels->begin(), labels->end(), PathLabel::Guess),
508                  PathLabel::SystemRegistry);
509
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)));
519 }
520
521 bool cmFindPackageCommand::InitialPass(std::vector<std::string> const& args)
522 {
523   if (args.empty()) {
524     this->SetError("called with incorrect number of arguments");
525     return false;
526   }
527
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]);
534   }
535
536   // Lookup target architecture, if any.
537   if (cmValue const arch =
538         this->Makefile->GetDefinition("CMAKE_LIBRARY_ARCHITECTURE")) {
539     this->LibraryArchitecture = *arch;
540   }
541
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;
547   }
548
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;
554   }
555
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;
561   }
562
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;
571   }
572
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;
582   }
583
584   // Check whether we should resolve symlinks when finding packages
585   if (this->Makefile->IsOn("CMAKE_FIND_PACKAGE_RESOLVE_SYMLINKS")) {
586     this->UseRealPath = true;
587   }
588
589   // Check if Sorting should be enabled
590   if (cmValue const so =
591         this->Makefile->GetDefinition("CMAKE_FIND_PACKAGE_SORT_ORDER")) {
592
593     if (*so == "NAME") {
594       this->SortOrder = Name_order;
595     } else if (*so == "NATURAL") {
596       this->SortOrder = Natural;
597     } else {
598       this->SortOrder = None;
599     }
600   }
601   if (cmValue const sd =
602         this->Makefile->GetDefinition("CMAKE_FIND_PACKAGE_SORT_DIRECTION")) {
603     this->SortDirection = (*sd == "ASC") ? Asc : Dec;
604   }
605
606   // Find what search path locations have been enabled/disable
607   this->SelectDefaultSearchModes();
608
609   // Find the current root path mode.
610   this->SelectDefaultRootPathMode();
611
612   // Find the current bundle/framework search policy.
613   this->SelectDefaultMacMode();
614
615   // Record options.
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;
623
624   // Always search directly in a generated path.
625   this->SearchPathSuffixes.emplace_back();
626
627   // Process debug mode
628   cmMakefile::DebugFindPkgRAII debugFindPkgRAII(this->Makefile, this->Name);
629   this->DebugMode = this->ComputeIfDebugModeWanted();
630
631   // Parse the arguments.
632   enum Doing
633   {
634     DoingNone,
635     DoingComponents,
636     DoingOptionalComponents,
637     DoingNames,
638     DoingPaths,
639     DoingPathSuffixes,
640     DoingConfigs,
641     DoingHints
642   };
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") {
651       this->Quiet = true;
652       doing = DoingNone;
653     } else if (args[i] == "BYPASS_PROVIDER") {
654       bypassProvider = true;
655       doing = DoingNone;
656     } else if (args[i] == "EXACT") {
657       this->VersionExact = true;
658       doing = DoingNone;
659     } else if (args[i] == "GLOBAL") {
660       this->GlobalScope = true;
661       doing = DoingNone;
662     } else if (args[i] == "MODULE") {
663       moduleArgs.push_back(i);
664       doing = DoingNone;
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);
669       doing = DoingNone;
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);
674       doing = DoingNone;
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);
684       doing = DoingNames;
685     } else if (args[i] == "PATHS") {
686       configArgs.push_back(i);
687       doing = DoingPaths;
688     } else if (args[i] == "HINTS") {
689       configArgs.push_back(i);
690       doing = DoingHints;
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;
699       doing = DoingNone;
700     } else if (args[i] == "NO_CMAKE_PACKAGE_REGISTRY") {
701       this->NoUserRegistry = true;
702       configArgs.push_back(i);
703       doing = DoingNone;
704     } else if (args[i] == "NO_CMAKE_SYSTEM_PACKAGE_REGISTRY") {
705       this->NoSystemRegistry = true;
706       configArgs.push_back(i);
707       doing = DoingNone;
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);
713       doing = DoingNone;
714     } else if (args[i] == "REGISTRY_VIEW") {
715       if (++i == args.size()) {
716         this->SetError("missing required argument for \"REGISTRY_VIEW\"");
717         return false;
718       }
719       auto view = cmWindowsRegistry::ToView(args[i]);
720       if (view) {
721         this->RegistryView = *view;
722         this->RegistryViewDefined = true;
723       } else {
724         this->SetError(
725           cmStrCat("given invalid value for \"REGISTRY_VIEW\": ", args[i]));
726         return false;
727       }
728     } else if (this->CheckCommonArgument(args[i])) {
729       configArgs.push_back(i);
730       doing = DoingNone;
731     } else if ((doing == DoingComponents) ||
732                (doing == DoingOptionalComponents)) {
733       // Set a variable telling the find script whether this component
734       // is required.
735       const char* isRequired = "1";
736       if (doing == DoingOptionalComponents) {
737         isRequired = "0";
738         optionalComponents.insert(args[i]);
739       } else {
740         requiredComponents.insert(args[i]);
741       }
742
743       componentVarDefs.emplace_back(this->Name + "_FIND_REQUIRED_" + args[i],
744                                     isRequired);
745
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."));
765         return false;
766       }
767       this->Configs.push_back(args[i]);
768     } else if (!haveVersion && versionRegex.find(args[i])) {
769       haveVersion = true;
770       this->VersionComplete = args[i];
771     } else {
772       this->SetError(
773         cmStrCat("called with invalid argument \"", args[i], "\""));
774       return false;
775     }
776   }
777
778   if (!this->GlobalScope) {
779     cmValue value(
780       this->Makefile->GetDefinition("CMAKE_FIND_PACKAGE_TARGETS_GLOBAL"));
781     this->GlobalScope = value.IsOn();
782   }
783
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()) {
789     this->SetError(
790       cmStrCat("called with components that are both required and "
791                "optional:\n",
792                cmWrap("  ", doubledComponents, "", "\n"), "\n"));
793     return false;
794   }
795
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";
804     }
805     e << "and options exclusive to Config mode:\n";
806     for (auto si : configArgs) {
807       e << "  " << args[si] << "\n";
808     }
809     e << "The options are incompatible.";
810     this->SetError(e.str());
811     return false;
812   }
813
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.");
820   }
821
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);
832
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);
836       }
837       if (components.empty()) {
838         std::string const components_var = this->Name + "_FIND_COMPONENTS";
839         components = this->Makefile->GetSafeDefinition(components_var);
840       }
841     }
842   }
843
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.");
848       return false;
849     }
850
851     this->Version = versionRegex.match(1);
852     this->VersionMax = versionRegex.match(5);
853     if (versionRegex.match(4) == "<"_s) {
854       this->VersionRangeMax = VERSION_ENDPOINT_EXCLUDED;
855     }
856     if (!this->VersionMax.empty()) {
857       this->VersionRange = this->VersionComplete;
858     }
859   }
860
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.");
870       return false;
871     }
872   }
873
874   if (this->VersionExact && !this->VersionRange.empty()) {
875     this->SetError("EXACT cannot be specified with a version range.");
876     return false;
877   }
878
879   if (!this->Version.empty()) {
880     this->VersionCount =
881       parseVersion(this->Version, this->VersionMajor, this->VersionMinor,
882                    this->VersionPatch, this->VersionTweak);
883   }
884   if (!this->VersionMax.empty()) {
885     this->VersionMaxCount = parseVersion(
886       this->VersionMax, this->VersionMaxMajor, this->VersionMaxMinor,
887       this->VersionMaxPatch, this->VersionMaxTweak);
888   }
889
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."));
901     } else {
902       this->Required = true;
903     }
904   }
905
906   std::string const disableFindPackageVar =
907     cmStrCat("CMAKE_DISABLE_FIND_PACKAGE_", this->Name);
908   if (this->Makefile->IsOn(disableFindPackageVar)) {
909     if (this->Required) {
910       this->SetError(
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."));
917       return false;
918     }
919     return true;
920   }
921
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.
926
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) {
935       this->DebugMessage(
936         "BYPASS_PROVIDER given, skipping dependency provider");
937     }
938   } else if (providerCommand) {
939     if (this->DebugMode) {
940       this->DebugMessage(cmStrCat("Trying dependency provider command: ",
941                                   state->GetDependencyProvider()->GetCommand(),
942                                   "()"));
943     }
944     std::vector<cmListFileArgument> listFileArgs(args.size() + 1);
945     listFileArgs[0] =
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);
951                    });
952     if (!providerCommand(listFileArgs, this->Status)) {
953       return false;
954     }
955     if (this->Makefile->IsOn(cmStrCat(this->Name, "_FOUND"))) {
956       if (this->DebugMode) {
957         this->DebugMessage("Package was found by the dependency provider");
958       }
959       this->AppendSuccessInformation();
960       return true;
961     }
962   }
963
964   {
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();
969
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);
975         CM_FALLTHROUGH;
976       case cmPolicies::OLD:
977         // OLD behavior is to ignore the <pkg>_ROOT variables.
978         break;
979       case cmPolicies::REQUIRED_IF_USED:
980       case cmPolicies::REQUIRED_ALWAYS:
981         this->Makefile->IssueMessage(
982           MessageType::FATAL_ERROR,
983           cmPolicies::GetRequiredPolicyError(cmPolicies::CMP0074));
984         break;
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());
990       } break;
991     }
992   }
993
994   this->SetModuleVariables(components, componentVarDefs);
995
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);
1003   }
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)) {
1025         return false;
1026       }
1027     }
1028
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);
1043       break;
1044     }
1045   }
1046
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;
1054     } else {
1055       if (this->FindPackageUsingModuleMode()) {
1056         loadedPackage = true;
1057       } else {
1058         // The package was not loaded. Report errors.
1059         if (this->HandlePackageMode(HandlePackageModeType::Module)) {
1060           loadedPackage = true;
1061         }
1062       }
1063     }
1064   } else {
1065     if (this->UseFindModules && this->FindPackageUsingModuleMode()) {
1066       loadedPackage = true;
1067     } else {
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 "
1075                 "and "
1076                 "no Find"
1077              << this->Name
1078              << ".cmake module is in CMAKE_MODULE_PATH.  "
1079                 "Add MODULE to exclusively request Module mode and fail if "
1080                 "Find"
1081              << this->Name
1082              << ".cmake is missing.  "
1083                 "Add CONFIG to exclusively request Config mode and search for "
1084                 "a "
1085                 "package configuration file provided by "
1086              << this->Name << " (" << this->Name << "Config.cmake or "
1087              << cmSystemTools::LowerCase(this->Name) << "-config.cmake).  ";
1088         } else {
1089           aw << "find_package called without NO_MODULE option and no "
1090                 "Find"
1091              << this->Name
1092              << ".cmake module is in CMAKE_MODULE_PATH.  "
1093                 "Add NO_MODULE to exclusively request Config mode and search "
1094                 "for a "
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.";
1100         }
1101         aw << "\n"
1102               "(Variable CMAKE_FIND_PACKAGE_WARN_NO_MODULE enabled this "
1103               "warning.)";
1104         this->Makefile->IssueMessage(MessageType::AUTHOR_WARNING, aw.str());
1105       }
1106
1107       if (this->FindPackageUsingConfigMode()) {
1108         loadedPackage = true;
1109       }
1110     }
1111   }
1112
1113   this->AppendSuccessInformation();
1114
1115   // Restore original state of "_FIND_" variables set in SetModuleVariables()
1116   this->RestoreFindDefinitions();
1117
1118   // Pop the package stack
1119   this->Makefile->FindPackageRootPathStack.pop_back();
1120
1121   if (!this->DebugBuffer.empty()) {
1122     this->DebugMessage(this->DebugBuffer);
1123   }
1124
1125   return loadedPackage;
1126 }
1127
1128 bool cmFindPackageCommand::FindPackageUsingModuleMode()
1129 {
1130   bool foundModule = false;
1131   if (!this->FindModule(foundModule)) {
1132     return false;
1133   }
1134   return foundModule;
1135 }
1136
1137 bool cmFindPackageCommand::FindPackageUsingConfigMode()
1138 {
1139   this->Variable = cmStrCat(this->Name, "_DIR");
1140
1141   // Add the default name.
1142   if (this->Names.empty()) {
1143     this->Names.push_back(this->Name);
1144   }
1145
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);
1151
1152       config = cmStrCat(cmSystemTools::LowerCase(n), "-config.cmake");
1153       this->Configs.push_back(std::move(config));
1154     }
1155   }
1156
1157   // get igonored paths from vars and reroot them.
1158   std::vector<std::string> ignored;
1159   this->GetIgnoredPaths(ignored);
1160   this->RerootPaths(ignored);
1161
1162   // Construct a set of ignored paths
1163   this->IgnoredPaths.clear();
1164   this->IgnoredPaths.insert(ignored.begin(), ignored.end());
1165
1166   // get igonored prefix paths from vars and reroot them.
1167   std::vector<std::string> ignoredPrefixes;
1168   this->GetIgnoredPrefixPaths(ignoredPrefixes);
1169   this->RerootPaths(ignoredPrefixes);
1170
1171   // Construct a set of ignored prefix paths
1172   this->IgnoredPrefixPaths.clear();
1173   this->IgnoredPrefixPaths.insert(ignoredPrefixes.begin(),
1174                                   ignoredPrefixes.end());
1175
1176   // Find and load the package.
1177   return this->HandlePackageMode(HandlePackageModeType::Config);
1178 }
1179
1180 void cmFindPackageCommand::SetVersionVariables(
1181   const std::function<void(const std::string&, cm::string_view)>&
1182     addDefinition,
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)
1186 {
1187   addDefinition(prefix, version);
1188
1189   char buf[64];
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);
1200 }
1201
1202 void cmFindPackageCommand::SetModuleVariables(
1203   const std::string& components,
1204   const std::vector<std::pair<std::string, const char*>>& componentVarDefs)
1205 {
1206   this->AddFindDefinition("CMAKE_FIND_PACKAGE_NAME", this->Name);
1207
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);
1213   }
1214
1215   if (this->Quiet) {
1216     // Tell the module that is about to be read that it should find
1217     // quietly.
1218     std::string quietly = cmStrCat(this->Name, "_FIND_QUIETLY");
1219     this->AddFindDefinition(quietly, "1"_s);
1220   }
1221
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);
1227   }
1228
1229   if (!this->VersionComplete.empty()) {
1230     std::string req = cmStrCat(this->Name, "_FIND_VERSION_COMPLETE");
1231     this->AddFindDefinition(req, this->VersionComplete);
1232   }
1233
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);
1239   };
1240
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);
1247
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);
1251   }
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);
1258
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);
1264
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);
1271   }
1272
1273   if (this->RegistryViewDefined) {
1274     this->AddFindDefinition(cmStrCat(this->Name, "_FIND_REGISTRY_VIEW"),
1275                             cmWindowsRegistry::FromView(this->RegistryView));
1276   }
1277 }
1278
1279 void cmFindPackageCommand::AddFindDefinition(const std::string& var,
1280                                              const cm::string_view value)
1281 {
1282   if (cmValue old = this->Makefile->GetDefinition(var)) {
1283     this->OriginalDefs[var].exists = true;
1284     this->OriginalDefs[var].value = *old;
1285   } else {
1286     this->OriginalDefs[var].exists = false;
1287   }
1288   this->Makefile->AddDefinition(var, value);
1289 }
1290
1291 void cmFindPackageCommand::RestoreFindDefinitions()
1292 {
1293   for (auto const& i : this->OriginalDefs) {
1294     OriginalDef const& od = i.second;
1295     if (od.exists) {
1296       this->Makefile->AddDefinition(i.first, od.value);
1297     } else {
1298       this->Makefile->RemoveDefinition(i.first);
1299     }
1300   }
1301 }
1302
1303 bool cmFindPackageCommand::FindModule(bool& found)
1304 {
1305   std::string moduleFileName = cmStrCat("Find", this->Name, ".cmake");
1306
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");
1315     } else {
1316       debugBuffer =
1317         cmStrCat(debugBuffer, "The file was found at\n  ", mfile, "\n");
1318     }
1319     this->DebugBuffer = cmStrCat(this->DebugBuffer, debugBuffer);
1320   }
1321
1322   if (!mfile.empty()) {
1323     if (system) {
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);
1328         switch (status) {
1329           case cmPolicies::WARN: {
1330             this->Makefile->IssueMessage(
1331               MessageType::AUTHOR_WARNING,
1332               cmStrCat(cmPolicies::GetPolicyWarning(it->second), "\n"));
1333             CM_FALLTHROUGH;
1334           }
1335           case cmPolicies::OLD:
1336             break;
1337           case cmPolicies::REQUIRED_IF_USED:
1338           case cmPolicies::REQUIRED_ALWAYS:
1339           case cmPolicies::NEW:
1340             return true;
1341         }
1342       }
1343     }
1344
1345     // Load the module we found, and set "<name>_FIND_MODULE" to true
1346     // while inside it.
1347     found = 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);
1352
1353     if (this->DebugMode) {
1354       std::string const foundVar = cmStrCat(this->Name, "_FOUND");
1355       if (this->Makefile->IsDefinitionSet(foundVar) &&
1356           !this->Makefile->IsOn(foundVar)) {
1357
1358         this->DebugBuffer = cmStrCat(
1359           this->DebugBuffer, "The module is considered not found due to ",
1360           foundVar, " being FALSE.");
1361       }
1362     }
1363     return result;
1364   }
1365   return true;
1366 }
1367
1368 bool cmFindPackageCommand::HandlePackageMode(
1369   const HandlePackageModeType handlePackageModeType)
1370 {
1371   this->ConsideredConfigs.clear();
1372
1373   // Try to find the config file.
1374   cmValue def = this->Makefile->GetDefinition(this->Variable);
1375
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);
1383
1384       // Treat relative paths with respect to the current source dir.
1385       if (!cmSystemTools::FileIsFullPath(dir)) {
1386         dir = "/" + dir;
1387         dir = this->Makefile->GetCurrentSourceDirectory() + dir;
1388       }
1389       // The file location was cached.  Look for the correct file.
1390       std::string file;
1391       if (this->FindConfigFile(dir, file)) {
1392         this->FileFound = file;
1393         fileFound = true;
1394       }
1395       def = this->Makefile->GetDefinition(this->Variable);
1396     }
1397
1398     // Search for the config file if it is not already found.
1399     if (cmIsOff(def) || !fileFound) {
1400       fileFound = this->FindConfig();
1401     }
1402
1403     // Sanity check.
1404     if (fileFound && this->FileFound.empty()) {
1405       this->Makefile->IssueMessage(
1406         MessageType::INTERNAL_ERROR,
1407         "fileFound is true but FileFound is empty!");
1408       fileFound = false;
1409     }
1410   }
1411
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;
1416
1417   // If the directory for the config file was found, try to read the file.
1418   bool result = true;
1419   bool found = false;
1420   bool configFileSetFOUNDFalse = false;
1421
1422   if (fileFound) {
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);
1430     }
1431     this->Makefile->RemoveDefinition(notFoundMessageVar);
1432
1433     // Set the version variables before loading the config file.
1434     // It may override them.
1435     this->StoreVersionFound();
1436
1437     // Parse the configuration file.
1438     if (this->ReadListFile(this->FileFound, DoPolicyScope)) {
1439       // The package has been found.
1440       found = true;
1441
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
1446         found = false;
1447         configFileSetFOUNDFalse = true;
1448         notFoundMessage =
1449           this->Makefile->GetSafeDefinition(notFoundMessageVar);
1450       }
1451     } else {
1452       // The configuration file is invalid.
1453       result = false;
1454     }
1455   }
1456
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.
1461     result = false;
1462   }
1463
1464   // package not found
1465   if (result && !found) {
1466     // warn if package required or neither quiet nor in config mode
1467     if (this->Required ||
1468         !(this->Quiet ||
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";
1483         }
1484       }
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
1490           << "\" that "
1491           << (this->VersionExact ? "exactly matches" : "is compatible with")
1492           << " requested version "
1493           << (this->VersionRange.empty() ? "" : "range ") << "\""
1494           << this->VersionComplete
1495           << "\".\n"
1496              "The following configuration files were considered but not "
1497              "accepted:\n";
1498
1499         for (ConfigFileInfo const& info :
1500              cmMakeRange(this->ConsideredConfigs.cbegin(), duplicate_end)) {
1501           e << "  " << info.filename << ", version: " << info.version << "\n";
1502         }
1503       } else {
1504         std::string requestedVersionString;
1505         if (!this->VersionComplete.empty()) {
1506           requestedVersionString =
1507             cmStrCat(" (requested version ", this->VersionComplete, ')');
1508         }
1509
1510         if (this->UseConfigFiles) {
1511           if (this->UseFindModules) {
1512             e << "By not providing \"Find" << this->Name
1513               << ".cmake\" in "
1514                  "CMAKE_MODULE_PATH this project has asked CMake to find a "
1515                  "package configuration file provided by \""
1516               << this->Name
1517               << "\", "
1518                  "but CMake did not find one.\n";
1519           }
1520
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";
1525           } else {
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";
1530           }
1531
1532           e << "Add the installation prefix of \"" << this->Name
1533             << "\" to "
1534                "CMAKE_PREFIX_PATH or set \""
1535             << this->Variable
1536             << "\" to a "
1537                "directory containing one of the above files. "
1538                "If \""
1539             << this->Name
1540             << "\" provides a separate development "
1541                "package or SDK, be sure it has been installed.";
1542         } else // if(!this->UseFindModules && !this->UseConfigFiles)
1543         {
1544           e << "No \"Find" << this->Name
1545             << ".cmake\" found in "
1546                "CMAKE_MODULE_PATH.";
1547
1548           aw
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 "
1557                "Find"
1558             << this->Name
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";
1563         }
1564       }
1565
1566       this->Makefile->IssueMessage(this->Required ? MessageType::FATAL_ERROR
1567                                                   : MessageType::WARNING,
1568                                    e.str());
1569       if (this->Required) {
1570         cmSystemTools::SetFatalErrorOccurred();
1571       }
1572
1573       if (!aw.str().empty()) {
1574         this->Makefile->IssueMessage(MessageType::AUTHOR_WARNING, aw.str());
1575       }
1576     }
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,
1581                                              "_DIR)"),
1582                                     -1);
1583     }
1584   }
1585
1586   // Set a variable marking whether the package was found.
1587   this->Makefile->AddDefinition(foundVar, found ? "1" : "0");
1588
1589   // Set a variable naming the configuration file that was found.
1590   std::string const fileVar = cmStrCat(this->Name, "_CONFIG");
1591   if (found) {
1592     this->Makefile->AddDefinition(fileVar, this->FileFound);
1593   } else {
1594     this->Makefile->RemoveDefinition(fileVar);
1595   }
1596
1597   std::string const consideredConfigsVar =
1598     cmStrCat(this->Name, "_CONSIDERED_CONFIGS");
1599   std::string const consideredVersionsVar =
1600     cmStrCat(this->Name, "_CONSIDERED_VERSIONS");
1601
1602   std::string consideredConfigFiles;
1603   std::string consideredVersions;
1604
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;
1611     sep = ";";
1612   }
1613
1614   this->Makefile->AddDefinition(consideredConfigsVar, consideredConfigFiles);
1615
1616   this->Makefile->AddDefinition(consideredVersionsVar, consideredVersions);
1617
1618   return result;
1619 }
1620
1621 bool cmFindPackageCommand::FindConfig()
1622 {
1623   // Compute the set of search prefixes.
1624   this->ComputePrefixes();
1625
1626   // Look for the project's configuration file.
1627   bool found = false;
1628   if (this->DebugMode) {
1629     this->DebugBuffer = cmStrCat(this->DebugBuffer,
1630                                  "find_package considered the following "
1631                                  "locations for ",
1632                                  this->Name, "'s Config module:\n");
1633   }
1634
1635   // Search for frameworks.
1636   if (!found && (this->SearchFrameworkFirst || this->SearchFrameworkOnly)) {
1637     found = this->FindFrameworkConfig();
1638   }
1639
1640   // Search for apps.
1641   if (!found && (this->SearchAppBundleFirst || this->SearchAppBundleOnly)) {
1642     found = this->FindAppBundleConfig();
1643   }
1644
1645   // Search prefixes.
1646   if (!found && !(this->SearchFrameworkOnly || this->SearchAppBundleOnly)) {
1647     found = this->FindPrefixedConfig();
1648   }
1649
1650   // Search for frameworks.
1651   if (!found && this->SearchFrameworkLast) {
1652     found = this->FindFrameworkConfig();
1653   }
1654
1655   // Search for apps.
1656   if (!found && this->SearchAppBundleLast) {
1657     found = this->FindAppBundleConfig();
1658   }
1659
1660   if (this->DebugMode) {
1661     if (found) {
1662       this->DebugBuffer = cmStrCat(
1663         this->DebugBuffer, "The file was found at\n  ", this->FileFound, "\n");
1664     } else {
1665       this->DebugBuffer =
1666         cmStrCat(this->DebugBuffer, "The file was not found.\n");
1667     }
1668   }
1669
1670   // Store the entry in the cache so it can be set by the user.
1671   std::string init;
1672   if (found) {
1673     init = cmSystemTools::GetFilenamePath(this->FileFound);
1674   } else {
1675     init = this->Variable + "-NOTFOUND";
1676   }
1677   // We force the value since we do not get here if it was already set.
1678   this->SetConfigDirCacheVariable(init);
1679
1680   return found;
1681 }
1682
1683 void cmFindPackageCommand::SetConfigDirCacheVariable(const std::string& value)
1684 {
1685   std::string const help =
1686     cmStrCat("The directory containing a CMake configuration file for ",
1687              this->Name, '.');
1688   this->Makefile->AddCacheDefinition(this->Variable, value, help.c_str(),
1689                                      cmStateEnums::PATH, true);
1690   if (this->Makefile->GetPolicyStatus(cmPolicies::CMP0126) ==
1691         cmPolicies::NEW &&
1692       this->Makefile->IsNormalDefinitionSet(this->Variable)) {
1693     this->Makefile->AddDefinition(this->Variable, value);
1694   }
1695 }
1696
1697 bool cmFindPackageCommand::FindPrefixedConfig()
1698 {
1699   std::vector<std::string> const& prefixes = this->SearchPaths;
1700   return std::any_of(
1701     prefixes.begin(), prefixes.end(),
1702     [this](std::string const& p) -> bool { return this->SearchPrefix(p); });
1703 }
1704
1705 bool cmFindPackageCommand::FindFrameworkConfig()
1706 {
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);
1711                      });
1712 }
1713
1714 bool cmFindPackageCommand::FindAppBundleConfig()
1715 {
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);
1720                      });
1721 }
1722
1723 bool cmFindPackageCommand::ReadListFile(const std::string& f,
1724                                         const PolicyScopeRule psr)
1725 {
1726   const bool noPolicyScope = !this->PolicyScope || psr == NoPolicyScope;
1727
1728   using ITScope = cmMakefile::ImportedTargetScope;
1729   ITScope scope = this->GlobalScope ? ITScope::Global : ITScope::Local;
1730   cmMakefile::SetGlobalTargetImportScope globScope(this->Makefile, scope);
1731
1732   if (this->Makefile->ReadDependentFile(f, noPolicyScope)) {
1733     return true;
1734   }
1735   std::string const e = cmStrCat("Error reading CMake code from \"", f, "\".");
1736   this->SetError(e);
1737   return false;
1738 }
1739
1740 void cmFindPackageCommand::AppendToFoundProperty(const bool found)
1741 {
1742   std::vector<std::string> foundContents;
1743   cmValue foundProp =
1744     this->Makefile->GetState()->GetGlobalProperty("PACKAGES_FOUND");
1745   if (cmNonempty(foundProp)) {
1746     cmExpandList(*foundProp, foundContents, false);
1747     auto nameIt =
1748       std::find(foundContents.begin(), foundContents.end(), this->Name);
1749     if (nameIt != foundContents.end()) {
1750       foundContents.erase(nameIt);
1751     }
1752   }
1753
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);
1759     auto nameIt =
1760       std::find(notFoundContents.begin(), notFoundContents.end(), this->Name);
1761     if (nameIt != notFoundContents.end()) {
1762       notFoundContents.erase(nameIt);
1763     }
1764   }
1765
1766   if (found) {
1767     foundContents.push_back(this->Name);
1768   } else {
1769     notFoundContents.push_back(this->Name);
1770   }
1771
1772   std::string tmp = cmJoin(foundContents, ";");
1773   this->Makefile->GetState()->SetGlobalProperty("PACKAGES_FOUND", tmp.c_str());
1774
1775   tmp = cmJoin(notFoundContents, ";");
1776   this->Makefile->GetState()->SetGlobalProperty("PACKAGES_NOT_FOUND",
1777                                                 tmp.c_str());
1778 }
1779
1780 void cmFindPackageCommand::AppendSuccessInformation()
1781 {
1782   {
1783     std::string const transitivePropName =
1784       cmStrCat("_CMAKE_", this->Name, "_TRANSITIVE_DEPENDENCY");
1785     this->Makefile->GetState()->SetGlobalProperty(transitivePropName, "False");
1786   }
1787   std::string const found = cmStrCat(this->Name, "_FOUND");
1788   std::string const upperFound = cmSystemTools::UpperCase(found);
1789
1790   bool const upperResult = this->Makefile->IsOn(upperFound);
1791   bool const result = this->Makefile->IsOn(found);
1792   bool const packageFound = (result || upperResult);
1793
1794   this->AppendToFoundProperty(packageFound);
1795
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");
1802
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()) {
1810     versionInfo =
1811       cmStrCat(this->VersionExact ? "==" : ">=", ' ', this->Version);
1812   }
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,
1819                                                   "REQUIRED");
1820   }
1821 }
1822
1823 void cmFindPackageCommand::ComputePrefixes()
1824 {
1825   this->FillPrefixesPackageRedirect();
1826
1827   if (!this->NoDefaultPath) {
1828     if (!this->NoPackageRootPath) {
1829       this->FillPrefixesPackageRoot();
1830     }
1831     if (!this->NoCMakePath) {
1832       this->FillPrefixesCMakeVariable();
1833     }
1834     if (!this->NoCMakeEnvironmentPath) {
1835       this->FillPrefixesCMakeEnvironment();
1836     }
1837   }
1838
1839   this->FillPrefixesUserHints();
1840
1841   if (!this->NoDefaultPath) {
1842     if (!this->NoSystemEnvironmentPath) {
1843       this->FillPrefixesSystemEnvironment();
1844     }
1845     if (!this->NoUserRegistry) {
1846       this->FillPrefixesUserRegistry();
1847     }
1848     if (!this->NoCMakeSystemPath) {
1849       this->FillPrefixesCMakeSystemVariable();
1850     }
1851     if (!this->NoSystemRegistry) {
1852       this->FillPrefixesSystemRegistry();
1853     }
1854   }
1855   this->FillPrefixesUserGuess();
1856
1857   this->ComputeFinalPaths(IgnorePaths::No);
1858 }
1859
1860 void cmFindPackageCommand::FillPrefixesPackageRedirect()
1861 {
1862   cmSearchPath& paths = this->LabeledPaths[PathLabel::PackageRedirect];
1863
1864   const auto redirectDir =
1865     this->Makefile->GetDefinition("CMAKE_FIND_PACKAGE_REDIRECTS_DIR");
1866   if (redirectDir && !redirectDir->empty()) {
1867     paths.AddPath(*redirectDir);
1868   }
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);
1874   }
1875 }
1876
1877 void cmFindPackageCommand::FillPrefixesPackageRoot()
1878 {
1879   cmSearchPath& paths = this->LabeledPaths[PathLabel::PackageRoot];
1880
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();
1884        ++pkgPaths) {
1885     for (std::string const& path : *pkgPaths) {
1886       paths.AddPath(path);
1887     }
1888   }
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);
1894   }
1895 }
1896
1897 void cmFindPackageCommand::FillPrefixesCMakeEnvironment()
1898 {
1899   cmSearchPath& paths = this->LabeledPaths[PathLabel::CMakeEnvironment];
1900   std::string debugBuffer;
1901   std::size_t debugOffset = 0;
1902
1903   // Check the environment variable with the same name as the cache
1904   // entry.
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);
1910   }
1911
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);
1919   }
1920
1921   paths.AddEnvPath("CMAKE_FRAMEWORK_PATH");
1922   paths.AddEnvPath("CMAKE_APPBUNDLE_PATH");
1923   if (this->DebugMode) {
1924     debugBuffer =
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);
1930   }
1931 }
1932
1933 void cmFindPackageCommand::FillPrefixesCMakeVariable()
1934 {
1935   cmSearchPath& paths = this->LabeledPaths[PathLabel::CMake];
1936   std::string debugBuffer;
1937   std::size_t debugOffset = 0;
1938
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);
1943   }
1944
1945   paths.AddCMakePath("CMAKE_FRAMEWORK_PATH");
1946   paths.AddCMakePath("CMAKE_APPBUNDLE_PATH");
1947   if (this->DebugMode) {
1948     debugBuffer =
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);
1954   }
1955 }
1956
1957 void cmFindPackageCommand::FillPrefixesSystemEnvironment()
1958 {
1959   cmSearchPath& paths = this->LabeledPaths[PathLabel::SystemEnvironment];
1960
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));
1970     } else {
1971       paths.AddPath(i);
1972     }
1973   }
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);
1979   }
1980 }
1981
1982 void cmFindPackageCommand::FillPrefixesUserRegistry()
1983 {
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)) ==
1989       B_OK) {
1990     std::string fname = cmStrCat(dir, "/cmake/packages/", Name);
1991     this->LoadPackageRegistryDir(fname,
1992                                  this->LabeledPaths[PathLabel::UserRegistry]);
1993   }
1994 #else
1995   std::string dir;
1996   if (cmSystemTools::GetEnv("HOME", dir)) {
1997     dir += "/.cmake/packages/";
1998     dir += this->Name;
1999     this->LoadPackageRegistryDir(dir,
2000                                  this->LabeledPaths[PathLabel::UserRegistry]);
2001   }
2002 #endif
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);
2009   }
2010 }
2011
2012 void cmFindPackageCommand::FillPrefixesSystemRegistry()
2013 {
2014   if (this->NoSystemRegistry || this->NoDefaultPath) {
2015     return;
2016   }
2017
2018 #if defined(_WIN32) && !defined(__CYGWIN__)
2019   this->LoadPackageRegistryWinSystem();
2020 #endif
2021
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);
2029   }
2030 }
2031
2032 #if defined(_WIN32) && !defined(__CYGWIN__)
2033 void cmFindPackageCommand::LoadPackageRegistryWinUser()
2034 {
2035   // HKEY_CURRENT_USER\\Software shares 32-bit and 64-bit views.
2036   this->LoadPackageRegistryWin(true, 0,
2037                                this->LabeledPaths[PathLabel::UserRegistry]);
2038 }
2039
2040 void cmFindPackageCommand::LoadPackageRegistryWinSystem()
2041 {
2042   cmSearchPath& paths = this->LabeledPaths[PathLabel::SystemRegistry];
2043
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);
2049   } else {
2050     this->LoadPackageRegistryWin(false, KEY_WOW64_32KEY, paths);
2051     this->LoadPackageRegistryWin(false, KEY_WOW64_64KEY, paths);
2052   }
2053 }
2054
2055 void cmFindPackageCommand::LoadPackageRegistryWin(const bool user,
2056                                                   const unsigned int view,
2057                                                   cmSearchPath& outPaths)
2058 {
2059   std::wstring key = L"Software\\Kitware\\CMake\\Packages\\";
2060   key += cmsys::Encoding::ToWide(this->Name);
2061   std::set<std::wstring> bad;
2062   HKEY hKey;
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);
2068     bool done = false;
2069     DWORD index = 0;
2070     while (!done) {
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)) {
2075         case ERROR_SUCCESS:
2076           ++index;
2077           if (valueType == REG_SZ) {
2078             data[dataSize] = 0;
2079             if (!this->CheckPackageRegistryEntry(
2080                   cmsys::Encoding::ToNarrow(&data[0]), outPaths)) {
2081               // The entry is invalid.
2082               bad.insert(name);
2083             }
2084           }
2085           break;
2086         case ERROR_MORE_DATA:
2087           data.resize((dataSize + sizeof(data[0]) - 1) / sizeof(data[0]));
2088           break;
2089         case ERROR_NO_MORE_ITEMS:
2090         default:
2091           done = true;
2092           break;
2093       }
2094     }
2095     RegCloseKey(hKey);
2096   }
2097
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());
2104     }
2105     RegCloseKey(hKey);
2106   }
2107 }
2108
2109 #else
2110 void cmFindPackageCommand::LoadPackageRegistryDir(std::string const& dir,
2111                                                   cmSearchPath& outPaths)
2112 {
2113   cmsys::Directory files;
2114   if (!files.Load(dir)) {
2115     return;
2116   }
2117
2118   std::string fname;
2119   for (unsigned long i = 0; i < files.GetNumberOfFiles(); ++i) {
2120     fname = cmStrCat(dir, '/', files.GetFile(i));
2121
2122     if (!cmSystemTools::FileIsDirectory(fname)) {
2123       // Hold this file hostage until it behaves.
2124       cmFindPackageCommandHoldFile holdFile(fname.c_str());
2125
2126       // Load the file.
2127       cmsys::ifstream fin(fname.c_str(), std::ios::in | std::ios::binary);
2128       std::string fentry;
2129       if (fin && cmSystemTools::GetLineFromStream(fin, fentry) &&
2130           this->CheckPackageRegistryEntry(fentry, outPaths)) {
2131         // The file references an existing package, so release it.
2132         holdFile.Release();
2133       }
2134     }
2135   }
2136
2137   // TODO: Wipe out the directory if it is empty.
2138 }
2139 #endif
2140
2141 bool cmFindPackageCommand::CheckPackageRegistryEntry(const std::string& fname,
2142                                                      cmSearchPath& outPaths)
2143 {
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));
2152       } else {
2153         outPaths.AddPath(fname);
2154       }
2155       return true;
2156     }
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.
2160     return false;
2161   }
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.
2165   return true;
2166 }
2167
2168 void cmFindPackageCommand::FillPrefixesCMakeSystemVariable()
2169 {
2170   cmSearchPath& paths = this->LabeledPaths[PathLabel::CMakeSystem];
2171
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");
2177
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.
2182   //
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);
2194   }
2195   if (cmValue install_value = this->Makefile->GetDefinition(
2196         "_CMAKE_SYSTEM_PREFIX_PATH_INSTALL_PREFIX_VALUE")) {
2197     install_path_to_remove = *install_value;
2198   }
2199
2200   if (remove_install_prefix && install_prefix_in_list &&
2201       install_prefix_count > 0 && !install_path_to_remove.empty()) {
2202
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);
2207     long count = 0;
2208     for (const auto& path : expanded) {
2209       bool const to_add =
2210         !(path == install_path_to_remove && ++count == install_prefix_count);
2211       if (to_add) {
2212         paths.AddPath(path);
2213       }
2214     }
2215   } else if (add_install_prefix && !install_prefix_in_list) {
2216     paths.AddCMakePath("CMAKE_INSTALL_PREFIX");
2217     paths.AddCMakePath("CMAKE_SYSTEM_PREFIX_PATH");
2218   } else {
2219     // Otherwise the current setup of `CMAKE_SYSTEM_PREFIX_PATH` is correct
2220     paths.AddCMakePath("CMAKE_SYSTEM_PREFIX_PATH");
2221   }
2222
2223   paths.AddCMakePath("CMAKE_SYSTEM_FRAMEWORK_PATH");
2224   paths.AddCMakePath("CMAKE_SYSTEM_APPBUNDLE_PATH");
2225
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);
2231   }
2232 }
2233
2234 void cmFindPackageCommand::FillPrefixesUserGuess()
2235 {
2236   cmSearchPath& paths = this->LabeledPaths[PathLabel::Guess];
2237
2238   for (std::string const& p : this->UserGuessArgs) {
2239     paths.AddUserPath(p);
2240   }
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);
2246   }
2247 }
2248
2249 void cmFindPackageCommand::FillPrefixesUserHints()
2250 {
2251   cmSearchPath& paths = this->LabeledPaths[PathLabel::Hints];
2252
2253   for (std::string const& p : this->UserHintsArgs) {
2254     paths.AddUserPath(p);
2255   }
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);
2261   }
2262 }
2263
2264 bool cmFindPackageCommand::SearchDirectory(std::string const& dir)
2265 {
2266   assert(!dir.empty() && dir.back() == '/');
2267
2268   // Check each path suffix on this directory.
2269   for (std::string const& s : this->SearchPathSuffixes) {
2270     std::string d = dir;
2271     if (!s.empty()) {
2272       d += s;
2273       d += '/';
2274     }
2275     if (this->CheckDirectory(d)) {
2276       return true;
2277     }
2278   }
2279   return false;
2280 }
2281
2282 bool cmFindPackageCommand::CheckDirectory(std::string const& dir)
2283 {
2284   assert(!dir.empty() && dir.back() == '/');
2285
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);
2291     return true;
2292   }
2293   return false;
2294 }
2295
2296 bool cmFindPackageCommand::FindConfigFile(std::string const& dir,
2297                                           std::string& file)
2298 {
2299   if (this->IgnoredPaths.count(dir)) {
2300     return false;
2301   }
2302
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");
2307     }
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);
2312       }
2313       return true;
2314     }
2315   }
2316   return false;
2317 }
2318
2319 bool cmFindPackageCommand::CheckVersion(std::string const& config_file)
2320 {
2321   bool result = false; // by default, assume the version is not ok.
2322   bool haveResult = false;
2323   std::string version = "unknown";
2324
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);
2328
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);
2333     haveResult = true;
2334   }
2335
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);
2340     haveResult = true;
2341   }
2342
2343   // If no version was requested a versionless package is acceptable.
2344   if (!haveResult && this->Version.empty()) {
2345     result = true;
2346   }
2347
2348   ConfigFileInfo configFileInfo;
2349   configFileInfo.filename = config_file;
2350   configFileInfo.version = version;
2351   this->ConsideredConfigs.push_back(std::move(configFileInfo));
2352
2353   return result;
2354 }
2355
2356 bool cmFindPackageCommand::CheckVersionFile(std::string const& version_file,
2357                                             std::string& result_version)
2358 {
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);
2364
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");
2370
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);
2375
2376   auto addDefinition = [this](const std::string& variable,
2377                               cm::string_view value) {
2378     this->Makefile->AddDefinition(variable, value);
2379   };
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);
2393
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);
2400   }
2401
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");
2411     }
2412
2413     // The package is suitable if the version is okay and not
2414     // explicitly unsuitable.
2415     suitable = !unsuitable && (okay || this->Version.empty());
2416     if (suitable) {
2417       // Get the version found.
2418       this->VersionFound =
2419         this->Makefile->GetSafeDefinition("PACKAGE_VERSION");
2420
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) {
2431         case 4:
2432           this->VersionFoundTweak = parsed_tweak;
2433           CM_FALLTHROUGH;
2434         case 3:
2435           this->VersionFoundPatch = parsed_patch;
2436           CM_FALLTHROUGH;
2437         case 2:
2438           this->VersionFoundMinor = parsed_minor;
2439           CM_FALLTHROUGH;
2440         case 1:
2441           this->VersionFoundMajor = parsed_major;
2442           CM_FALLTHROUGH;
2443         default:
2444           break;
2445       }
2446     }
2447   }
2448
2449   result_version = this->Makefile->GetSafeDefinition("PACKAGE_VERSION");
2450   if (result_version.empty()) {
2451     result_version = "unknown";
2452   }
2453
2454   // Succeed if the version is suitable.
2455   return suitable;
2456 }
2457
2458 void cmFindPackageCommand::StoreVersionFound()
2459 {
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);
2465   };
2466
2467   this->SetVersionVariables(addDefinition, ver, this->VersionFound,
2468                             this->VersionFoundCount, this->VersionFoundMajor,
2469                             this->VersionFoundMinor, this->VersionFoundPatch,
2470                             this->VersionFoundTweak);
2471
2472   if (this->VersionFound.empty()) {
2473     this->Makefile->RemoveDefinition(ver);
2474   }
2475 }
2476
2477 bool cmFindPackageCommand::SearchPrefix(std::string const& prefix_in)
2478 {
2479   assert(!prefix_in.empty() && prefix_in.back() == '/');
2480
2481   // Skip this if the prefix does not exist.
2482   if (!cmSystemTools::FileIsDirectory(prefix_in)) {
2483     return false;
2484   }
2485
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);
2490   }
2491   if (this->IgnoredPaths.count(prefixWithoutSlash) ||
2492       this->IgnoredPrefixPaths.count(prefixWithoutSlash)) {
2493     return false;
2494   }
2495
2496   // PREFIX/ (useful on windows or in build trees)
2497   if (this->SearchDirectory(prefix_in)) {
2498     return true;
2499   }
2500
2501   // Strip the trailing slash because the path generator is about to
2502   // add one.
2503   std::string const prefix = prefix_in.substr(0, prefix_in.size() - 1);
2504
2505   auto searchFn = [this](const std::string& fullPath) -> bool {
2506     return this->SearchDirectory(fullPath);
2507   };
2508
2509   auto iCMakeGen = cmCaseInsensitiveDirectoryListGenerator{ "cmake"_s };
2510   auto firstPkgDirGen =
2511     cmProjectDirectoryListGenerator{ this->Names, this->SortOrder,
2512                                      this->SortDirection };
2513
2514   // PREFIX/(cmake|CMake)/ (useful on windows or in build trees)
2515   if (TryGeneratedPaths(searchFn, prefix, iCMakeGen)) {
2516     return true;
2517   }
2518
2519   // PREFIX/(Foo|foo|FOO).*/
2520   if (TryGeneratedPaths(searchFn, prefix, firstPkgDirGen)) {
2521     return true;
2522   }
2523
2524   // PREFIX/(Foo|foo|FOO).*/(cmake|CMake)/
2525   if (TryGeneratedPaths(searchFn, prefix, firstPkgDirGen, iCMakeGen)) {
2526     return true;
2527   }
2528
2529   auto secondPkgDirGen =
2530     cmProjectDirectoryListGenerator{ this->Names, this->SortOrder,
2531                                      this->SortDirection };
2532
2533   // PREFIX/(Foo|foo|FOO).*/(cmake|CMake)/(Foo|foo|FOO).*/
2534   if (TryGeneratedPaths(searchFn, prefix, firstPkgDirGen, iCMakeGen,
2535                         secondPkgDirGen)) {
2536     return true;
2537   }
2538
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);
2545   }
2546   if (this->UseLib32Paths) {
2547     common.emplace_back("lib32"_s);
2548   }
2549   if (this->UseLib64Paths) {
2550     common.emplace_back("lib64"_s);
2551   }
2552   if (this->UseLibx32Paths) {
2553     common.emplace_back("libx32"_s);
2554   }
2555   common.emplace_back("lib"_s);
2556   common.emplace_back("share"_s);
2557
2558   auto cmnGen = cmEnumPathSegmentsGenerator{ common };
2559   auto cmakeGen = cmAppendPathSegmentGenerator{ "cmake"_s };
2560
2561   // PREFIX/(lib/ARCH|lib*|share)/cmake/(Foo|foo|FOO).*/
2562   if (TryGeneratedPaths(searchFn, prefix, cmnGen, cmakeGen, firstPkgDirGen)) {
2563     return true;
2564   }
2565
2566   // PREFIX/(lib/ARCH|lib*|share)/(Foo|foo|FOO).*/
2567   if (TryGeneratedPaths(searchFn, prefix, cmnGen, firstPkgDirGen)) {
2568     return true;
2569   }
2570
2571   // PREFIX/(lib/ARCH|lib*|share)/(Foo|foo|FOO).*/(cmake|CMake)/
2572   if (TryGeneratedPaths(searchFn, prefix, cmnGen, firstPkgDirGen, iCMakeGen)) {
2573     return true;
2574   }
2575
2576   // PREFIX/(Foo|foo|FOO).*/(lib/ARCH|lib*|share)/cmake/(Foo|foo|FOO).*/
2577   if (TryGeneratedPaths(searchFn, prefix, firstPkgDirGen, cmnGen, cmakeGen,
2578                         secondPkgDirGen)) {
2579     return true;
2580   }
2581
2582   // PREFIX/(Foo|foo|FOO).*/(lib/ARCH|lib*|share)/(Foo|foo|FOO).*/
2583   if (TryGeneratedPaths(searchFn, prefix, firstPkgDirGen, cmnGen,
2584                         secondPkgDirGen)) {
2585     return true;
2586   }
2587
2588   // PREFIX/(Foo|foo|FOO).*/(lib/ARCH|lib*|share)/(Foo|foo|FOO).*/(cmake|CMake)/
2589   return TryGeneratedPaths(searchFn, prefix, firstPkgDirGen, cmnGen,
2590                            secondPkgDirGen, iCMakeGen);
2591 }
2592
2593 bool cmFindPackageCommand::SearchFrameworkPrefix(std::string const& prefix_in)
2594 {
2595   assert(!prefix_in.empty() && prefix_in.back() == '/');
2596
2597   // Strip the trailing slash because the path generator is about to
2598   // add one.
2599   std::string const prefix = prefix_in.substr(0, prefix_in.size() - 1);
2600
2601   auto searchFn = [this](const std::string& fullPath) -> bool {
2602     return this->SearchDirectory(fullPath);
2603   };
2604
2605   auto iCMakeGen = cmCaseInsensitiveDirectoryListGenerator{ "cmake"_s };
2606   auto fwGen =
2607     cmMacProjectDirectoryListGenerator{ this->Names, ".framework"_s };
2608   auto rGen = cmAppendPathSegmentGenerator{ "Resources"_s };
2609   auto vGen = cmAppendPathSegmentGenerator{ "Versions"_s };
2610   auto grGen = cmFileListGeneratorGlob{ "/*/Resources"_s };
2611
2612   // <prefix>/Foo.framework/Resources/
2613   if (TryGeneratedPaths(searchFn, prefix, fwGen, rGen)) {
2614     return true;
2615   }
2616
2617   // <prefix>/Foo.framework/Resources/CMake/
2618   if (TryGeneratedPaths(searchFn, prefix, fwGen, rGen, iCMakeGen)) {
2619     return true;
2620   }
2621
2622   // <prefix>/Foo.framework/Versions/*/Resources/
2623   if (TryGeneratedPaths(searchFn, prefix, fwGen, vGen, grGen)) {
2624     return true;
2625   }
2626
2627   // <prefix>/Foo.framework/Versions/*/Resources/CMake/
2628   return TryGeneratedPaths(searchFn, prefix, fwGen, vGen, grGen, iCMakeGen);
2629 }
2630
2631 bool cmFindPackageCommand::SearchAppBundlePrefix(std::string const& prefix_in)
2632 {
2633   assert(!prefix_in.empty() && prefix_in.back() == '/');
2634
2635   // Strip the trailing slash because the path generator is about to
2636   // add one.
2637   std::string const prefix = prefix_in.substr(0, prefix_in.size() - 1);
2638
2639   auto searchFn = [this](const std::string& fullPath) -> bool {
2640     return this->SearchDirectory(fullPath);
2641   };
2642
2643   auto appGen = cmMacProjectDirectoryListGenerator{ this->Names, ".app"_s };
2644   auto crGen = cmAppendPathSegmentGenerator{ "Contents/Resources"_s };
2645
2646   // <prefix>/Foo.app/Contents/Resources
2647   if (TryGeneratedPaths(searchFn, prefix, appGen, crGen)) {
2648     return true;
2649   }
2650
2651   // <prefix>/Foo.app/Contents/Resources/CMake
2652   return TryGeneratedPaths(
2653     searchFn, prefix, appGen, crGen,
2654     cmCaseInsensitiveDirectoryListGenerator{ "cmake"_s });
2655 }
2656
2657 // TODO: Debug cmsys::Glob double slash problem.
2658
2659 bool cmFindPackage(std::vector<std::string> const& args,
2660                    cmExecutionStatus& status)
2661 {
2662   return cmFindPackageCommand(status).InitialPass(args);
2663 }