cmFindPackageCommand.cxx 89 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661
  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. #include <algorithm>
  5. #include <cassert>
  6. #include <cstdio>
  7. #include <deque>
  8. #include <functional>
  9. #include <iterator>
  10. #include <sstream>
  11. #include <utility>
  12. #include <cm/memory>
  13. #include <cm/optional>
  14. #include <cmext/string_view>
  15. #include "cmsys/Directory.hxx"
  16. #include "cmsys/FStream.hxx"
  17. #include "cmsys/Glob.hxx"
  18. #include "cmsys/RegularExpression.hxx"
  19. #include "cmsys/String.h"
  20. #include "cmAlgorithms.h"
  21. #include "cmDependencyProvider.h"
  22. #include "cmListFileCache.h"
  23. #include "cmMakefile.h"
  24. #include "cmMessageType.h"
  25. #include "cmPolicies.h"
  26. #include "cmRange.h"
  27. #include "cmSearchPath.h"
  28. #include "cmState.h"
  29. #include "cmStateTypes.h"
  30. #include "cmStringAlgorithms.h"
  31. #include "cmSystemTools.h"
  32. #include "cmValue.h"
  33. #include "cmVersion.h"
  34. #include "cmWindowsRegistry.h"
  35. #if defined(__HAIKU__)
  36. # include <FindDirectory.h>
  37. # include <StorageDefs.h>
  38. #endif
  39. #if defined(_WIN32) && !defined(__CYGWIN__)
  40. # include <windows.h>
  41. // http://msdn.microsoft.com/en-us/library/aa384253%28v=vs.85%29.aspx
  42. # if !defined(KEY_WOW64_32KEY)
  43. # define KEY_WOW64_32KEY 0x0200
  44. # endif
  45. # if !defined(KEY_WOW64_64KEY)
  46. # define KEY_WOW64_64KEY 0x0100
  47. # endif
  48. #endif
  49. class cmExecutionStatus;
  50. namespace {
  51. template <template <typename> class Op>
  52. struct StrverscmpOp
  53. {
  54. bool operator()(const std::string& lhs, const std::string& rhs) const
  55. {
  56. return Op<int>()(cmSystemTools::strverscmp(lhs, rhs), 0);
  57. }
  58. };
  59. std::size_t collectPathsForDebug(std::string& buffer,
  60. cmSearchPath const& searchPath,
  61. std::size_t const startIndex = 0)
  62. {
  63. const auto& paths = searchPath.GetPaths();
  64. if (paths.empty()) {
  65. buffer += " none\n";
  66. return 0;
  67. }
  68. for (auto i = startIndex; i < paths.size(); i++) {
  69. buffer += " " + paths[i].Path + "\n";
  70. }
  71. return paths.size();
  72. }
  73. #if !(defined(_WIN32) && !defined(__CYGWIN__))
  74. class cmFindPackageCommandHoldFile
  75. {
  76. const char* File;
  77. public:
  78. cmFindPackageCommandHoldFile(const char* const f)
  79. : File(f)
  80. {
  81. }
  82. ~cmFindPackageCommandHoldFile()
  83. {
  84. if (this->File) {
  85. cmSystemTools::RemoveFile(this->File);
  86. }
  87. }
  88. cmFindPackageCommandHoldFile(const cmFindPackageCommandHoldFile&) = delete;
  89. cmFindPackageCommandHoldFile& operator=(
  90. const cmFindPackageCommandHoldFile&) = delete;
  91. void Release() { this->File = nullptr; }
  92. };
  93. #endif
  94. bool isDirentryToIgnore(const char* const fname)
  95. {
  96. assert(fname != nullptr);
  97. assert(fname[0] != 0);
  98. return fname[0] == '.' &&
  99. (fname[1] == 0 || (fname[1] == '.' && fname[2] == 0));
  100. }
  101. class cmAppendPathSegmentGenerator
  102. {
  103. public:
  104. cmAppendPathSegmentGenerator(cm::string_view dirName)
  105. : DirName{ dirName }
  106. {
  107. }
  108. std::string GetNextCandidate(const std::string& parent)
  109. {
  110. if (this->NeedReset) {
  111. return {};
  112. }
  113. this->NeedReset = true;
  114. return cmStrCat(parent, '/', this->DirName);
  115. }
  116. void Reset() { this->NeedReset = false; }
  117. private:
  118. const cm::string_view DirName;
  119. bool NeedReset = false;
  120. };
  121. class cmEnumPathSegmentsGenerator
  122. {
  123. public:
  124. cmEnumPathSegmentsGenerator(const std::vector<cm::string_view>& init)
  125. : Names{ init }
  126. , Current{ this->Names.get().cbegin() }
  127. {
  128. }
  129. std::string GetNextCandidate(const std::string& parent)
  130. {
  131. if (this->Current != this->Names.get().cend()) {
  132. return cmStrCat(parent, '/', *this->Current++);
  133. }
  134. return {};
  135. }
  136. void Reset() { this->Current = this->Names.get().cbegin(); }
  137. private:
  138. std::reference_wrapper<const std::vector<cm::string_view>> Names;
  139. std::vector<cm::string_view>::const_iterator Current;
  140. };
  141. class cmCaseInsensitiveDirectoryListGenerator
  142. {
  143. public:
  144. cmCaseInsensitiveDirectoryListGenerator(cm::string_view name)
  145. : DirectoryLister{}
  146. , DirName{ name }
  147. {
  148. }
  149. std::string GetNextCandidate(const std::string& parent)
  150. {
  151. if (!this->Loaded) {
  152. this->CurrentIdx = 0ul;
  153. this->Loaded = true;
  154. if (!this->DirectoryLister.Load(parent)) {
  155. return {};
  156. }
  157. }
  158. while (this->CurrentIdx < this->DirectoryLister.GetNumberOfFiles()) {
  159. const char* const fname =
  160. this->DirectoryLister.GetFile(this->CurrentIdx++);
  161. if (isDirentryToIgnore(fname)) {
  162. continue;
  163. }
  164. if (cmsysString_strcasecmp(fname, this->DirName.data()) == 0) {
  165. auto candidate = cmStrCat(parent, '/', fname);
  166. if (cmSystemTools::FileIsDirectory(candidate)) {
  167. return candidate;
  168. }
  169. }
  170. }
  171. return {};
  172. }
  173. void Reset() { this->Loaded = false; }
  174. private:
  175. cmsys::Directory DirectoryLister;
  176. const cm::string_view DirName;
  177. unsigned long CurrentIdx = 0ul;
  178. bool Loaded = false;
  179. };
  180. class cmDirectoryListGenerator
  181. {
  182. public:
  183. cmDirectoryListGenerator(std::vector<std::string> const& names)
  184. : Names{ names }
  185. , Matches{}
  186. , Current{ this->Matches.cbegin() }
  187. {
  188. }
  189. virtual ~cmDirectoryListGenerator() = default;
  190. std::string GetNextCandidate(const std::string& parent)
  191. {
  192. // Construct a list of matches if not yet
  193. if (this->Matches.empty()) {
  194. cmsys::Directory directoryLister;
  195. // ALERT `Directory::Load()` keeps only names
  196. // internally and LOST entry type from `dirent`.
  197. // So, `Directory::FileIsDirectory` gonna use
  198. // `SystemTools::FileIsDirectory()` and waste a syscall.
  199. // TODO Need to enhance the `Directory` class.
  200. directoryLister.Load(parent);
  201. // ATTENTION Is it guaranteed that first two entries are
  202. // `.` and `..`?
  203. // TODO If so, just start with index 2 and drop the
  204. // `isDirentryToIgnore(i)` condition to check.
  205. for (auto i = 0ul; i < directoryLister.GetNumberOfFiles(); ++i) {
  206. const char* const fname = directoryLister.GetFile(i);
  207. if (isDirentryToIgnore(fname)) {
  208. continue;
  209. }
  210. for (const auto& n : this->Names.get()) {
  211. // NOTE Customization point for `cmMacProjectDirectoryListGenerator`
  212. const auto name = this->TransformNameBeforeCmp(n);
  213. // Skip entries that don't match and non-directories.
  214. // ATTENTION BTW, original code also didn't check if it's a symlink
  215. // to a directory!
  216. const auto equal =
  217. (cmsysString_strncasecmp(fname, name.c_str(), name.length()) == 0);
  218. if (equal && directoryLister.FileIsDirectory(i)) {
  219. this->Matches.emplace_back(fname);
  220. }
  221. }
  222. }
  223. // NOTE Customization point for `cmProjectDirectoryListGenerator`
  224. this->OnMatchesLoaded();
  225. this->Current = this->Matches.cbegin();
  226. }
  227. if (this->Current != this->Matches.cend()) {
  228. auto candidate = cmStrCat(parent, '/', *this->Current++);
  229. return candidate;
  230. }
  231. return {};
  232. }
  233. void Reset()
  234. {
  235. this->Matches.clear();
  236. this->Current = this->Matches.cbegin();
  237. }
  238. protected:
  239. virtual void OnMatchesLoaded() {}
  240. virtual std::string TransformNameBeforeCmp(std::string same) { return same; }
  241. std::reference_wrapper<const std::vector<std::string>> Names;
  242. std::vector<std::string> Matches;
  243. std::vector<std::string>::const_iterator Current;
  244. };
  245. class cmProjectDirectoryListGenerator : public cmDirectoryListGenerator
  246. {
  247. public:
  248. cmProjectDirectoryListGenerator(std::vector<std::string> const& names,
  249. cmFindPackageCommand::SortOrderType so,
  250. cmFindPackageCommand::SortDirectionType sd)
  251. : cmDirectoryListGenerator{ names }
  252. , SortOrder{ so }
  253. , SortDirection{ sd }
  254. {
  255. }
  256. void OnMatchesLoaded() override
  257. {
  258. // check if there is a specific sorting order to perform
  259. if (this->SortOrder != cmFindPackageCommand::None) {
  260. cmFindPackageCommand::Sort(this->Matches.begin(), this->Matches.end(),
  261. this->SortOrder, this->SortDirection);
  262. }
  263. }
  264. private:
  265. // sort parameters
  266. const cmFindPackageCommand::SortOrderType SortOrder;
  267. const cmFindPackageCommand::SortDirectionType SortDirection;
  268. };
  269. class cmMacProjectDirectoryListGenerator : public cmDirectoryListGenerator
  270. {
  271. public:
  272. cmMacProjectDirectoryListGenerator(const std::vector<std::string>& names,
  273. cm::string_view ext)
  274. : cmDirectoryListGenerator{ names }
  275. , Extension{ ext }
  276. {
  277. }
  278. std::string TransformNameBeforeCmp(std::string name) override
  279. {
  280. return cmStrCat(name, this->Extension);
  281. }
  282. private:
  283. const cm::string_view Extension;
  284. };
  285. class cmFileListGeneratorGlob
  286. {
  287. public:
  288. cmFileListGeneratorGlob(cm::string_view pattern)
  289. : Pattern(pattern)
  290. , Files{}
  291. , Current{}
  292. {
  293. }
  294. std::string GetNextCandidate(const std::string& parent)
  295. {
  296. if (this->Files.empty()) {
  297. // Glob the set of matching files.
  298. std::string expr = cmStrCat(parent, this->Pattern);
  299. cmsys::Glob g;
  300. if (!g.FindFiles(expr)) {
  301. return {};
  302. }
  303. this->Files = g.GetFiles();
  304. this->Current = this->Files.cbegin();
  305. }
  306. // Skip non-directories
  307. for (; this->Current != this->Files.cend() &&
  308. !cmSystemTools::FileIsDirectory(*this->Current);
  309. ++this->Current) {
  310. }
  311. return (this->Current != this->Files.cend()) ? *this->Current++
  312. : std::string{};
  313. }
  314. void Reset()
  315. {
  316. this->Files.clear();
  317. this->Current = this->Files.cbegin();
  318. }
  319. private:
  320. cm::string_view Pattern;
  321. std::vector<std::string> Files;
  322. std::vector<std::string>::const_iterator Current;
  323. };
  324. #if defined(__LCC__)
  325. # define CM_LCC_DIAG_SUPPRESS_1222
  326. # pragma diag_suppress 1222 // invalid error number (3288, but works anyway)
  327. # define CM_LCC_DIAG_SUPPRESS_3288
  328. # pragma diag_suppress 3288 // parameter was declared but never referenced
  329. #endif
  330. void ResetGenerator()
  331. {
  332. }
  333. template <typename Generator>
  334. void ResetGenerator(Generator&& generator)
  335. {
  336. std::forward<Generator&&>(generator).Reset();
  337. }
  338. template <typename Generator, typename... Generators>
  339. void ResetGenerator(Generator&& generator, Generators&&... generators)
  340. {
  341. ResetGenerator(std::forward<Generator&&>(generator));
  342. ResetGenerator(std::forward<Generators&&>(generators)...);
  343. }
  344. template <typename CallbackFn>
  345. bool TryGeneratedPaths(CallbackFn&& filesCollector,
  346. const std::string& fullPath)
  347. {
  348. assert(!fullPath.empty() && fullPath.back() != '/');
  349. return std::forward<CallbackFn&&>(filesCollector)(fullPath + '/');
  350. }
  351. template <typename CallbackFn, typename Generator, typename... Rest>
  352. bool TryGeneratedPaths(CallbackFn&& filesCollector,
  353. const std::string& startPath, Generator&& gen,
  354. Rest&&... tail)
  355. {
  356. ResetGenerator(std::forward<Generator&&>(gen));
  357. for (auto path = gen.GetNextCandidate(startPath); !path.empty();
  358. path = gen.GetNextCandidate(startPath)) {
  359. ResetGenerator(std::forward<Rest&&>(tail)...);
  360. if (TryGeneratedPaths(std::forward<CallbackFn&&>(filesCollector), path,
  361. std::forward<Rest&&>(tail)...)) {
  362. return true;
  363. }
  364. }
  365. return false;
  366. }
  367. #ifdef CM_LCC_DIAG_SUPPRESS_3288
  368. # undef CM_LCC_DIAG_SUPPRESS_3288
  369. # pragma diag_default 3288
  370. #endif
  371. #ifdef CM_LCC_DIAG_SUPPRESS_1222
  372. # undef CM_LCC_DIAG_SUPPRESS_1222
  373. # pragma diag_default 1222
  374. #endif
  375. // Parse the version number and store the results that were
  376. // successfully parsed.
  377. int parseVersion(const std::string& version, unsigned int& major,
  378. unsigned int& minor, unsigned int& patch, unsigned int& tweak)
  379. {
  380. return std::sscanf(version.c_str(), "%u.%u.%u.%u", &major, &minor, &patch,
  381. &tweak);
  382. }
  383. } // anonymous namespace
  384. cmFindPackageCommand::PathLabel
  385. cmFindPackageCommand::PathLabel::PackageRedirect("PACKAGE_REDIRECT");
  386. cmFindPackageCommand::PathLabel cmFindPackageCommand::PathLabel::UserRegistry(
  387. "PACKAGE_REGISTRY");
  388. cmFindPackageCommand::PathLabel cmFindPackageCommand::PathLabel::Builds(
  389. "BUILDS");
  390. cmFindPackageCommand::PathLabel
  391. cmFindPackageCommand::PathLabel::SystemRegistry("SYSTEM_PACKAGE_REGISTRY");
  392. const cm::string_view cmFindPackageCommand::VERSION_ENDPOINT_INCLUDED(
  393. "INCLUDE");
  394. const cm::string_view cmFindPackageCommand::VERSION_ENDPOINT_EXCLUDED(
  395. "EXCLUDE");
  396. void cmFindPackageCommand::Sort(std::vector<std::string>::iterator begin,
  397. std::vector<std::string>::iterator end,
  398. SortOrderType const order,
  399. SortDirectionType const dir)
  400. {
  401. if (order == Name_order) {
  402. if (dir == Dec) {
  403. std::sort(begin, end, std::greater<std::string>());
  404. } else {
  405. std::sort(begin, end);
  406. }
  407. } else if (order == Natural) {
  408. // natural order uses letters and numbers (contiguous numbers digit are
  409. // compared such that e.g. 000 00 < 01 < 010 < 09 < 0 < 1 < 9 < 10
  410. if (dir == Dec) {
  411. std::sort(begin, end, StrverscmpOp<std::greater>());
  412. } else {
  413. std::sort(begin, end, StrverscmpOp<std::less>());
  414. }
  415. }
  416. // else do not sort
  417. }
  418. cmFindPackageCommand::cmFindPackageCommand(cmExecutionStatus& status)
  419. : cmFindCommon(status)
  420. , VersionRangeMin(VERSION_ENDPOINT_INCLUDED)
  421. , VersionRangeMax(VERSION_ENDPOINT_INCLUDED)
  422. {
  423. this->CMakePathName = "PACKAGE";
  424. this->DebugMode = false;
  425. this->AppendSearchPathGroups();
  426. this->DeprecatedFindModules["Qt"] = cmPolicies::CMP0084;
  427. }
  428. void cmFindPackageCommand::AppendSearchPathGroups()
  429. {
  430. // Update the All group with new paths. Note that package redirection must
  431. // take precedence over everything else, so it has to be first in the array.
  432. std::vector<cmFindCommon::PathLabel>* const labels =
  433. &this->PathGroupLabelMap[PathGroup::All];
  434. labels->insert(labels->begin(), PathLabel::PackageRedirect);
  435. labels->insert(
  436. std::find(labels->begin(), labels->end(), PathLabel::CMakeSystem),
  437. PathLabel::UserRegistry);
  438. labels->insert(
  439. std::find(labels->begin(), labels->end(), PathLabel::CMakeSystem),
  440. PathLabel::Builds);
  441. labels->insert(std::find(labels->begin(), labels->end(), PathLabel::Guess),
  442. PathLabel::SystemRegistry);
  443. // Create the new path objects
  444. this->LabeledPaths.insert(
  445. std::make_pair(PathLabel::PackageRedirect, cmSearchPath(this)));
  446. this->LabeledPaths.insert(
  447. std::make_pair(PathLabel::UserRegistry, cmSearchPath(this)));
  448. this->LabeledPaths.insert(
  449. std::make_pair(PathLabel::Builds, cmSearchPath(this)));
  450. this->LabeledPaths.insert(
  451. std::make_pair(PathLabel::SystemRegistry, cmSearchPath(this)));
  452. }
  453. bool cmFindPackageCommand::InitialPass(std::vector<std::string> const& args)
  454. {
  455. if (args.empty()) {
  456. this->SetError("called with incorrect number of arguments");
  457. return false;
  458. }
  459. // Lookup required version of CMake.
  460. if (cmValue const rv =
  461. this->Makefile->GetDefinition("CMAKE_MINIMUM_REQUIRED_VERSION")) {
  462. unsigned int v[3] = { 0, 0, 0 };
  463. std::sscanf(rv->c_str(), "%u.%u.%u", &v[0], &v[1], &v[2]);
  464. this->RequiredCMakeVersion = CMake_VERSION_ENCODE(v[0], v[1], v[2]);
  465. }
  466. // Lookup target architecture, if any.
  467. if (cmValue const arch =
  468. this->Makefile->GetDefinition("CMAKE_LIBRARY_ARCHITECTURE")) {
  469. this->LibraryArchitecture = *arch;
  470. }
  471. // Lookup whether lib32 paths should be used.
  472. if (this->Makefile->PlatformIs32Bit() &&
  473. this->Makefile->GetState()->GetGlobalPropertyAsBool(
  474. "FIND_LIBRARY_USE_LIB32_PATHS")) {
  475. this->UseLib32Paths = true;
  476. }
  477. // Lookup whether lib64 paths should be used.
  478. if (this->Makefile->PlatformIs64Bit() &&
  479. this->Makefile->GetState()->GetGlobalPropertyAsBool(
  480. "FIND_LIBRARY_USE_LIB64_PATHS")) {
  481. this->UseLib64Paths = true;
  482. }
  483. // Lookup whether libx32 paths should be used.
  484. if (this->Makefile->PlatformIsx32() &&
  485. this->Makefile->GetState()->GetGlobalPropertyAsBool(
  486. "FIND_LIBRARY_USE_LIBX32_PATHS")) {
  487. this->UseLibx32Paths = true;
  488. }
  489. // Check if User Package Registry should be disabled
  490. // The `CMAKE_FIND_USE_PACKAGE_REGISTRY` has
  491. // priority over the deprecated CMAKE_FIND_PACKAGE_NO_PACKAGE_REGISTRY
  492. if (cmValue const def =
  493. this->Makefile->GetDefinition("CMAKE_FIND_USE_PACKAGE_REGISTRY")) {
  494. this->NoUserRegistry = !cmIsOn(*def);
  495. } else if (this->Makefile->IsOn("CMAKE_FIND_PACKAGE_NO_PACKAGE_REGISTRY")) {
  496. this->NoUserRegistry = true;
  497. }
  498. // Check if System Package Registry should be disabled
  499. // The `CMAKE_FIND_USE_SYSTEM_PACKAGE_REGISTRY` has
  500. // priority over the deprecated CMAKE_FIND_PACKAGE_NO_SYSTEM_PACKAGE_REGISTRY
  501. if (cmValue const def = this->Makefile->GetDefinition(
  502. "CMAKE_FIND_USE_SYSTEM_PACKAGE_REGISTRY")) {
  503. this->NoSystemRegistry = !cmIsOn(*def);
  504. } else if (this->Makefile->IsOn(
  505. "CMAKE_FIND_PACKAGE_NO_SYSTEM_PACKAGE_REGISTRY")) {
  506. this->NoSystemRegistry = true;
  507. }
  508. // Check whether we should resolve symlinks when finding packages
  509. if (this->Makefile->IsOn("CMAKE_FIND_PACKAGE_RESOLVE_SYMLINKS")) {
  510. this->UseRealPath = true;
  511. }
  512. // Check if Sorting should be enabled
  513. if (cmValue const so =
  514. this->Makefile->GetDefinition("CMAKE_FIND_PACKAGE_SORT_ORDER")) {
  515. if (*so == "NAME") {
  516. this->SortOrder = Name_order;
  517. } else if (*so == "NATURAL") {
  518. this->SortOrder = Natural;
  519. } else {
  520. this->SortOrder = None;
  521. }
  522. }
  523. if (cmValue const sd =
  524. this->Makefile->GetDefinition("CMAKE_FIND_PACKAGE_SORT_DIRECTION")) {
  525. this->SortDirection = (*sd == "ASC") ? Asc : Dec;
  526. }
  527. // Find what search path locations have been enabled/disable
  528. this->SelectDefaultSearchModes();
  529. // Find the current root path mode.
  530. this->SelectDefaultRootPathMode();
  531. // Find the current bundle/framework search policy.
  532. this->SelectDefaultMacMode();
  533. // Record options.
  534. this->Name = args[0];
  535. std::string components;
  536. const char* components_sep = "";
  537. std::set<std::string> requiredComponents;
  538. std::set<std::string> optionalComponents;
  539. std::vector<std::pair<std::string, const char*>> componentVarDefs;
  540. bool bypassProvider = false;
  541. // Always search directly in a generated path.
  542. this->SearchPathSuffixes.emplace_back();
  543. // Process debug mode
  544. cmMakefile::DebugFindPkgRAII debugFindPkgRAII(this->Makefile, this->Name);
  545. this->DebugMode = this->ComputeIfDebugModeWanted();
  546. // Parse the arguments.
  547. enum Doing
  548. {
  549. DoingNone,
  550. DoingComponents,
  551. DoingOptionalComponents,
  552. DoingNames,
  553. DoingPaths,
  554. DoingPathSuffixes,
  555. DoingConfigs,
  556. DoingHints
  557. };
  558. Doing doing = DoingNone;
  559. cmsys::RegularExpression versionRegex(
  560. R"V(^([0-9]+(\.[0-9]+)*)(\.\.\.(<?)([0-9]+(\.[0-9]+)*))?$)V");
  561. bool haveVersion = false;
  562. std::vector<std::size_t> configArgs;
  563. std::vector<std::size_t> moduleArgs;
  564. for (std::size_t i = 1u; i < args.size(); ++i) {
  565. if (args[i] == "QUIET") {
  566. this->Quiet = true;
  567. doing = DoingNone;
  568. } else if (args[i] == "BYPASS_PROVIDER") {
  569. bypassProvider = true;
  570. doing = DoingNone;
  571. } else if (args[i] == "EXACT") {
  572. this->VersionExact = true;
  573. doing = DoingNone;
  574. } else if (args[i] == "GLOBAL") {
  575. this->GlobalScope = true;
  576. doing = DoingNone;
  577. } else if (args[i] == "MODULE") {
  578. moduleArgs.push_back(i);
  579. doing = DoingNone;
  580. // XXX(clang-tidy): https://bugs.llvm.org/show_bug.cgi?id=44165
  581. // NOLINTNEXTLINE(bugprone-branch-clone)
  582. } else if (args[i] == "CONFIG") {
  583. configArgs.push_back(i);
  584. doing = DoingNone;
  585. // XXX(clang-tidy): https://bugs.llvm.org/show_bug.cgi?id=44165
  586. // NOLINTNEXTLINE(bugprone-branch-clone)
  587. } else if (args[i] == "NO_MODULE") {
  588. configArgs.push_back(i);
  589. doing = DoingNone;
  590. } else if (args[i] == "REQUIRED") {
  591. this->Required = true;
  592. doing = DoingComponents;
  593. } else if (args[i] == "COMPONENTS") {
  594. doing = DoingComponents;
  595. } else if (args[i] == "OPTIONAL_COMPONENTS") {
  596. doing = DoingOptionalComponents;
  597. } else if (args[i] == "NAMES") {
  598. configArgs.push_back(i);
  599. doing = DoingNames;
  600. } else if (args[i] == "PATHS") {
  601. configArgs.push_back(i);
  602. doing = DoingPaths;
  603. } else if (args[i] == "HINTS") {
  604. configArgs.push_back(i);
  605. doing = DoingHints;
  606. } else if (args[i] == "PATH_SUFFIXES") {
  607. configArgs.push_back(i);
  608. doing = DoingPathSuffixes;
  609. } else if (args[i] == "CONFIGS") {
  610. configArgs.push_back(i);
  611. doing = DoingConfigs;
  612. } else if (args[i] == "NO_POLICY_SCOPE") {
  613. this->PolicyScope = false;
  614. doing = DoingNone;
  615. } else if (args[i] == "NO_CMAKE_PACKAGE_REGISTRY") {
  616. this->NoUserRegistry = true;
  617. configArgs.push_back(i);
  618. doing = DoingNone;
  619. } else if (args[i] == "NO_CMAKE_SYSTEM_PACKAGE_REGISTRY") {
  620. this->NoSystemRegistry = true;
  621. configArgs.push_back(i);
  622. doing = DoingNone;
  623. // XXX(clang-tidy): https://bugs.llvm.org/show_bug.cgi?id=44165
  624. // NOLINTNEXTLINE(bugprone-branch-clone)
  625. } else if (args[i] == "NO_CMAKE_BUILDS_PATH") {
  626. // Ignore legacy option.
  627. configArgs.push_back(i);
  628. doing = DoingNone;
  629. } else if (args[i] == "REGISTRY_VIEW") {
  630. if (++i == args.size()) {
  631. this->SetError("missing required argument for \"REGISTRY_VIEW\"");
  632. return false;
  633. }
  634. auto view = cmWindowsRegistry::ToView(args[i]);
  635. if (view) {
  636. this->RegistryView = *view;
  637. this->RegistryViewDefined = true;
  638. } else {
  639. this->SetError(
  640. cmStrCat("given invalid value for \"REGISTRY_VIEW\": ", args[i]));
  641. return false;
  642. }
  643. } else if (this->CheckCommonArgument(args[i])) {
  644. configArgs.push_back(i);
  645. doing = DoingNone;
  646. } else if ((doing == DoingComponents) ||
  647. (doing == DoingOptionalComponents)) {
  648. // Set a variable telling the find script whether this component
  649. // is required.
  650. const char* isRequired = "1";
  651. if (doing == DoingOptionalComponents) {
  652. isRequired = "0";
  653. optionalComponents.insert(args[i]);
  654. } else {
  655. requiredComponents.insert(args[i]);
  656. }
  657. componentVarDefs.emplace_back(this->Name + "_FIND_REQUIRED_" + args[i],
  658. isRequired);
  659. // Append to the list of required components.
  660. components += components_sep;
  661. components += args[i];
  662. components_sep = ";";
  663. } else if (doing == DoingNames) {
  664. this->Names.push_back(args[i]);
  665. } else if (doing == DoingPaths) {
  666. this->UserGuessArgs.push_back(args[i]);
  667. } else if (doing == DoingHints) {
  668. this->UserHintsArgs.push_back(args[i]);
  669. } else if (doing == DoingPathSuffixes) {
  670. this->AddPathSuffix(args[i]);
  671. } else if (doing == DoingConfigs) {
  672. if (args[i].find_first_of(":/\\") != std::string::npos ||
  673. cmSystemTools::GetFilenameLastExtension(args[i]) != ".cmake") {
  674. this->SetError(cmStrCat(
  675. "given CONFIGS option followed by invalid file name \"", args[i],
  676. "\". The names given must be file names without "
  677. "a path and with a \".cmake\" extension."));
  678. return false;
  679. }
  680. this->Configs.push_back(args[i]);
  681. } else if (!haveVersion && versionRegex.find(args[i])) {
  682. haveVersion = true;
  683. this->VersionComplete = args[i];
  684. } else {
  685. this->SetError(
  686. cmStrCat("called with invalid argument \"", args[i], "\""));
  687. return false;
  688. }
  689. }
  690. if (!this->GlobalScope) {
  691. cmValue value(
  692. this->Makefile->GetDefinition("CMAKE_FIND_PACKAGE_TARGETS_GLOBAL"));
  693. this->GlobalScope = value.IsOn();
  694. }
  695. std::vector<std::string> doubledComponents;
  696. std::set_intersection(requiredComponents.begin(), requiredComponents.end(),
  697. optionalComponents.begin(), optionalComponents.end(),
  698. std::back_inserter(doubledComponents));
  699. if (!doubledComponents.empty()) {
  700. this->SetError(
  701. cmStrCat("called with components that are both required and "
  702. "optional:\n",
  703. cmWrap(" ", doubledComponents, "", "\n"), "\n"));
  704. return false;
  705. }
  706. // Check and eliminate search modes not allowed by the args provided
  707. this->UseFindModules = configArgs.empty();
  708. this->UseConfigFiles = moduleArgs.empty();
  709. if (!this->UseFindModules && !this->UseConfigFiles) {
  710. std::ostringstream e;
  711. e << "given options exclusive to Module mode:\n";
  712. for (auto si : moduleArgs) {
  713. e << " " << args[si] << "\n";
  714. }
  715. e << "and options exclusive to Config mode:\n";
  716. for (auto si : configArgs) {
  717. e << " " << args[si] << "\n";
  718. }
  719. e << "The options are incompatible.";
  720. this->SetError(e.str());
  721. return false;
  722. }
  723. // Ignore EXACT with no version.
  724. if (this->VersionComplete.empty() && this->VersionExact) {
  725. this->VersionExact = false;
  726. this->Makefile->IssueMessage(
  727. MessageType::AUTHOR_WARNING,
  728. "Ignoring EXACT since no version is requested.");
  729. }
  730. if (this->VersionComplete.empty() || components.empty()) {
  731. // Check whether we are recursing inside "Find<name>.cmake" within
  732. // another find_package(<name>) call.
  733. std::string const mod = cmStrCat(this->Name, "_FIND_MODULE");
  734. if (this->Makefile->IsOn(mod)) {
  735. if (this->VersionComplete.empty()) {
  736. // Get version information from the outer call if necessary.
  737. // Requested version string.
  738. std::string const ver = cmStrCat(this->Name, "_FIND_VERSION_COMPLETE");
  739. this->VersionComplete = this->Makefile->GetSafeDefinition(ver);
  740. // Whether an exact version is required.
  741. std::string const exact = cmStrCat(this->Name, "_FIND_VERSION_EXACT");
  742. this->VersionExact = this->Makefile->IsOn(exact);
  743. }
  744. if (components.empty()) {
  745. std::string const components_var = this->Name + "_FIND_COMPONENTS";
  746. components = this->Makefile->GetSafeDefinition(components_var);
  747. }
  748. }
  749. }
  750. // fill various parts of version specification
  751. if (!this->VersionComplete.empty()) {
  752. if (!versionRegex.find(this->VersionComplete)) {
  753. this->SetError("called with invalid version specification.");
  754. return false;
  755. }
  756. this->Version = versionRegex.match(1);
  757. this->VersionMax = versionRegex.match(5);
  758. if (versionRegex.match(4) == "<"_s) {
  759. this->VersionRangeMax = VERSION_ENDPOINT_EXCLUDED;
  760. }
  761. if (!this->VersionMax.empty()) {
  762. this->VersionRange = this->VersionComplete;
  763. }
  764. }
  765. if (!this->VersionRange.empty()) {
  766. // version range must not be empty
  767. if ((this->VersionRangeMax == VERSION_ENDPOINT_INCLUDED &&
  768. cmSystemTools::VersionCompareGreater(this->Version,
  769. this->VersionMax)) ||
  770. (this->VersionRangeMax == VERSION_ENDPOINT_EXCLUDED &&
  771. cmSystemTools::VersionCompareGreaterEq(this->Version,
  772. this->VersionMax))) {
  773. this->SetError("specified version range is empty.");
  774. return false;
  775. }
  776. }
  777. if (this->VersionExact && !this->VersionRange.empty()) {
  778. this->SetError("EXACT cannot be specified with a version range.");
  779. return false;
  780. }
  781. if (!this->Version.empty()) {
  782. this->VersionCount =
  783. parseVersion(this->Version, this->VersionMajor, this->VersionMinor,
  784. this->VersionPatch, this->VersionTweak);
  785. }
  786. if (!this->VersionMax.empty()) {
  787. this->VersionMaxCount = parseVersion(
  788. this->VersionMax, this->VersionMaxMajor, this->VersionMaxMinor,
  789. this->VersionMaxPatch, this->VersionMaxTweak);
  790. }
  791. const std::string makePackageRequiredVar =
  792. cmStrCat("CMAKE_REQUIRE_FIND_PACKAGE_", this->Name);
  793. const bool makePackageRequiredSet =
  794. this->Makefile->IsOn(makePackageRequiredVar);
  795. if (makePackageRequiredSet) {
  796. if (this->Required) {
  797. this->Makefile->IssueMessage(
  798. MessageType::WARNING,
  799. cmStrCat("for module ", this->Name,
  800. " already called with REQUIRED, thus ",
  801. makePackageRequiredVar, " has no effect."));
  802. } else {
  803. this->Required = true;
  804. }
  805. }
  806. std::string const disableFindPackageVar =
  807. cmStrCat("CMAKE_DISABLE_FIND_PACKAGE_", this->Name);
  808. if (this->Makefile->IsOn(disableFindPackageVar)) {
  809. if (this->Required) {
  810. this->SetError(
  811. cmStrCat("for module ", this->Name,
  812. (makePackageRequiredSet
  813. ? " was made REQUIRED with " + makePackageRequiredVar
  814. : " called with REQUIRED, "),
  815. " but ", disableFindPackageVar,
  816. " is enabled. A REQUIRED package cannot be disabled."));
  817. return false;
  818. }
  819. return true;
  820. }
  821. // Now choose what method(s) we will use to satisfy the request. Note that
  822. // we still want all the above checking of arguments, etc. regardless of the
  823. // method used. This will ensure ill-formed arguments are caught earlier,
  824. // before things like dependency providers need to deal with them.
  825. // A dependency provider (if set) gets first look before other methods.
  826. // We do this before modifying the package root path stack because a
  827. // provider might use methods that ignore that.
  828. cmState* const state = this->Makefile->GetState();
  829. cmState::Command const providerCommand = state->GetDependencyProviderCommand(
  830. cmDependencyProvider::Method::FindPackage);
  831. if (bypassProvider) {
  832. if (this->DebugMode && providerCommand) {
  833. this->DebugMessage(
  834. "BYPASS_PROVIDER given, skipping dependency provider");
  835. }
  836. } else if (providerCommand) {
  837. if (this->DebugMode) {
  838. this->DebugMessage(cmStrCat("Trying dependency provider command: ",
  839. state->GetDependencyProvider()->GetCommand(),
  840. "()"));
  841. }
  842. std::vector<cmListFileArgument> listFileArgs(args.size() + 1);
  843. listFileArgs[0] =
  844. cmListFileArgument("FIND_PACKAGE", cmListFileArgument::Unquoted, 0);
  845. std::transform(args.begin(), args.end(), listFileArgs.begin() + 1,
  846. [](const std::string& arg) {
  847. return cmListFileArgument(arg,
  848. cmListFileArgument::Bracket, 0);
  849. });
  850. if (!providerCommand(listFileArgs, this->Status)) {
  851. return false;
  852. }
  853. if (this->Makefile->IsOn(cmStrCat(this->Name, "_FOUND"))) {
  854. if (this->DebugMode) {
  855. this->DebugMessage("Package was found by the dependency provider");
  856. }
  857. this->AppendSuccessInformation();
  858. return true;
  859. }
  860. }
  861. {
  862. // Allocate a PACKAGE_ROOT_PATH for the current find_package call.
  863. this->Makefile->FindPackageRootPathStack.emplace_back();
  864. std::vector<std::string>& rootPaths =
  865. this->Makefile->FindPackageRootPathStack.back();
  866. // Add root paths from <PackageName>_ROOT CMake and environment variables,
  867. // subject to CMP0074.
  868. switch (this->Makefile->GetPolicyStatus(cmPolicies::CMP0074)) {
  869. case cmPolicies::WARN:
  870. this->Makefile->MaybeWarnCMP0074(this->Name);
  871. CM_FALLTHROUGH;
  872. case cmPolicies::OLD:
  873. // OLD behavior is to ignore the <pkg>_ROOT variables.
  874. break;
  875. case cmPolicies::REQUIRED_IF_USED:
  876. case cmPolicies::REQUIRED_ALWAYS:
  877. this->Makefile->IssueMessage(
  878. MessageType::FATAL_ERROR,
  879. cmPolicies::GetRequiredPolicyError(cmPolicies::CMP0074));
  880. break;
  881. case cmPolicies::NEW: {
  882. // NEW behavior is to honor the <pkg>_ROOT variables.
  883. std::string const rootVar = this->Name + "_ROOT";
  884. this->Makefile->GetDefExpandList(rootVar, rootPaths, false);
  885. cmSystemTools::GetPath(rootPaths, rootVar.c_str());
  886. } break;
  887. }
  888. }
  889. this->SetModuleVariables(components, componentVarDefs);
  890. // See if we have been told to delegate to FetchContent or some other
  891. // redirected config package first. We have to check all names that
  892. // find_package() may look for, but only need to invoke the override for the
  893. // first one that matches.
  894. auto overrideNames = this->Names;
  895. if (overrideNames.empty()) {
  896. overrideNames.push_back(this->Name);
  897. }
  898. bool forceConfigMode = false;
  899. const auto redirectsDir =
  900. this->Makefile->GetSafeDefinition("CMAKE_FIND_PACKAGE_REDIRECTS_DIR");
  901. for (const auto& overrideName : overrideNames) {
  902. const auto nameLower = cmSystemTools::LowerCase(overrideName);
  903. const auto delegatePropName =
  904. cmStrCat("_FetchContent_", nameLower, "_override_find_package");
  905. const cmValue delegateToFetchContentProp =
  906. this->Makefile->GetState()->GetGlobalProperty(delegatePropName);
  907. if (delegateToFetchContentProp.IsOn()) {
  908. // When this property is set, the FetchContent module has already been
  909. // included at least once, so we know the FetchContent_MakeAvailable()
  910. // command will be defined. Any future find_package() calls after this
  911. // one for this package will by-pass this once-only delegation.
  912. // The following call will typically create a <name>-config.cmake file
  913. // in the redirectsDir, which we still want to process like any other
  914. // config file to ensure we follow normal find_package() processing.
  915. cmListFileFunction func(
  916. "FetchContent_MakeAvailable", 0, 0,
  917. { cmListFileArgument(overrideName, cmListFileArgument::Unquoted, 0) });
  918. if (!this->Makefile->ExecuteCommand(func, this->Status)) {
  919. return false;
  920. }
  921. }
  922. if (cmSystemTools::FileExists(
  923. cmStrCat(redirectsDir, '/', nameLower, "-config.cmake")) ||
  924. cmSystemTools::FileExists(
  925. cmStrCat(redirectsDir, '/', overrideName, "Config.cmake"))) {
  926. // Force the use of this redirected config package file, regardless of
  927. // the type of find_package() call. Files in the redirectsDir must always
  928. // take priority over everything else.
  929. forceConfigMode = true;
  930. this->UseConfigFiles = true;
  931. this->UseFindModules = false;
  932. this->Names.clear();
  933. this->Names.emplace_back(overrideName); // Force finding this one
  934. this->Variable = cmStrCat(this->Name, "_DIR");
  935. this->SetConfigDirCacheVariable(redirectsDir);
  936. break;
  937. }
  938. }
  939. // See if there is a Find<PackageName>.cmake module.
  940. bool loadedPackage = false;
  941. if (forceConfigMode) {
  942. loadedPackage = this->FindPackageUsingConfigMode();
  943. } else if (this->Makefile->IsOn("CMAKE_FIND_PACKAGE_PREFER_CONFIG")) {
  944. if (this->UseConfigFiles && this->FindPackageUsingConfigMode()) {
  945. loadedPackage = true;
  946. } else {
  947. if (this->FindPackageUsingModuleMode()) {
  948. loadedPackage = true;
  949. } else {
  950. // The package was not loaded. Report errors.
  951. if (this->HandlePackageMode(HandlePackageModeType::Module)) {
  952. loadedPackage = true;
  953. }
  954. }
  955. }
  956. } else {
  957. if (this->UseFindModules && this->FindPackageUsingModuleMode()) {
  958. loadedPackage = true;
  959. } else {
  960. // Handle CMAKE_FIND_PACKAGE_WARN_NO_MODULE (warn when CONFIG mode is
  961. // implicitly assumed)
  962. if (this->UseFindModules && this->UseConfigFiles &&
  963. this->Makefile->IsOn("CMAKE_FIND_PACKAGE_WARN_NO_MODULE")) {
  964. std::ostringstream aw;
  965. if (this->RequiredCMakeVersion >= CMake_VERSION_ENCODE(2, 8, 8)) {
  966. aw << "find_package called without either MODULE or CONFIG option "
  967. "and "
  968. "no Find"
  969. << this->Name
  970. << ".cmake module is in CMAKE_MODULE_PATH. "
  971. "Add MODULE to exclusively request Module mode and fail if "
  972. "Find"
  973. << this->Name
  974. << ".cmake is missing. "
  975. "Add CONFIG to exclusively request Config mode and search for "
  976. "a "
  977. "package configuration file provided by "
  978. << this->Name << " (" << this->Name << "Config.cmake or "
  979. << cmSystemTools::LowerCase(this->Name) << "-config.cmake). ";
  980. } else {
  981. aw << "find_package called without NO_MODULE option and no "
  982. "Find"
  983. << this->Name
  984. << ".cmake module is in CMAKE_MODULE_PATH. "
  985. "Add NO_MODULE to exclusively request Config mode and search "
  986. "for a "
  987. "package configuration file provided by "
  988. << this->Name << " (" << this->Name << "Config.cmake or "
  989. << cmSystemTools::LowerCase(this->Name)
  990. << "-config.cmake). Otherwise make Find" << this->Name
  991. << ".cmake available in CMAKE_MODULE_PATH.";
  992. }
  993. aw << "\n"
  994. "(Variable CMAKE_FIND_PACKAGE_WARN_NO_MODULE enabled this "
  995. "warning.)";
  996. this->Makefile->IssueMessage(MessageType::AUTHOR_WARNING, aw.str());
  997. }
  998. if (this->FindPackageUsingConfigMode()) {
  999. loadedPackage = true;
  1000. }
  1001. }
  1002. }
  1003. this->AppendSuccessInformation();
  1004. // Restore original state of "_FIND_" variables set in SetModuleVariables()
  1005. this->RestoreFindDefinitions();
  1006. // Pop the package stack
  1007. this->Makefile->FindPackageRootPathStack.pop_back();
  1008. if (!this->DebugBuffer.empty()) {
  1009. this->DebugMessage(this->DebugBuffer);
  1010. }
  1011. return loadedPackage;
  1012. }
  1013. bool cmFindPackageCommand::FindPackageUsingModuleMode()
  1014. {
  1015. bool foundModule = false;
  1016. if (!this->FindModule(foundModule)) {
  1017. return false;
  1018. }
  1019. return foundModule;
  1020. }
  1021. bool cmFindPackageCommand::FindPackageUsingConfigMode()
  1022. {
  1023. this->Variable = cmStrCat(this->Name, "_DIR");
  1024. // Add the default name.
  1025. if (this->Names.empty()) {
  1026. this->Names.push_back(this->Name);
  1027. }
  1028. // Add the default configs.
  1029. if (this->Configs.empty()) {
  1030. for (std::string const& n : this->Names) {
  1031. std::string config = cmStrCat(n, "Config.cmake");
  1032. this->Configs.push_back(config);
  1033. config = cmStrCat(cmSystemTools::LowerCase(n), "-config.cmake");
  1034. this->Configs.push_back(std::move(config));
  1035. }
  1036. }
  1037. // get igonored paths from vars and reroot them.
  1038. std::vector<std::string> ignored;
  1039. this->GetIgnoredPaths(ignored);
  1040. this->RerootPaths(ignored);
  1041. // Construct a set of ignored paths
  1042. this->IgnoredPaths.clear();
  1043. this->IgnoredPaths.insert(ignored.begin(), ignored.end());
  1044. // get igonored prefix paths from vars and reroot them.
  1045. std::vector<std::string> ignoredPrefixes;
  1046. this->GetIgnoredPrefixPaths(ignoredPrefixes);
  1047. this->RerootPaths(ignoredPrefixes);
  1048. // Construct a set of ignored prefix paths
  1049. this->IgnoredPrefixPaths.clear();
  1050. this->IgnoredPrefixPaths.insert(ignoredPrefixes.begin(),
  1051. ignoredPrefixes.end());
  1052. // Find and load the package.
  1053. return this->HandlePackageMode(HandlePackageModeType::Config);
  1054. }
  1055. void cmFindPackageCommand::SetVersionVariables(
  1056. const std::function<void(const std::string&, cm::string_view)>&
  1057. addDefinition,
  1058. const std::string& prefix, const std::string& version,
  1059. const unsigned int count, const unsigned int major, const unsigned int minor,
  1060. const unsigned int patch, const unsigned int tweak)
  1061. {
  1062. addDefinition(prefix, version);
  1063. char buf[64];
  1064. snprintf(buf, sizeof(buf), "%u", major);
  1065. addDefinition(prefix + "_MAJOR", buf);
  1066. snprintf(buf, sizeof(buf), "%u", minor);
  1067. addDefinition(prefix + "_MINOR", buf);
  1068. snprintf(buf, sizeof(buf), "%u", patch);
  1069. addDefinition(prefix + "_PATCH", buf);
  1070. snprintf(buf, sizeof(buf), "%u", tweak);
  1071. addDefinition(prefix + "_TWEAK", buf);
  1072. snprintf(buf, sizeof(buf), "%u", count);
  1073. addDefinition(prefix + "_COUNT", buf);
  1074. }
  1075. void cmFindPackageCommand::SetModuleVariables(
  1076. const std::string& components,
  1077. const std::vector<std::pair<std::string, const char*>>& componentVarDefs)
  1078. {
  1079. this->AddFindDefinition("CMAKE_FIND_PACKAGE_NAME", this->Name);
  1080. // Store the list of components and associated variable definitions
  1081. std::string components_var = this->Name + "_FIND_COMPONENTS";
  1082. this->AddFindDefinition(components_var, components);
  1083. for (const auto& varDef : componentVarDefs) {
  1084. this->AddFindDefinition(varDef.first, varDef.second);
  1085. }
  1086. if (this->Quiet) {
  1087. // Tell the module that is about to be read that it should find
  1088. // quietly.
  1089. std::string quietly = cmStrCat(this->Name, "_FIND_QUIETLY");
  1090. this->AddFindDefinition(quietly, "1"_s);
  1091. }
  1092. if (this->Required) {
  1093. // Tell the module that is about to be read that it should report
  1094. // a fatal error if the package is not found.
  1095. std::string req = cmStrCat(this->Name, "_FIND_REQUIRED");
  1096. this->AddFindDefinition(req, "1"_s);
  1097. }
  1098. if (!this->VersionComplete.empty()) {
  1099. std::string req = cmStrCat(this->Name, "_FIND_VERSION_COMPLETE");
  1100. this->AddFindDefinition(req, this->VersionComplete);
  1101. }
  1102. // Tell the module that is about to be read what version of the
  1103. // package has been requested.
  1104. auto addDefinition = [this](const std::string& variable,
  1105. cm::string_view value) {
  1106. this->AddFindDefinition(variable, value);
  1107. };
  1108. if (!this->Version.empty()) {
  1109. auto prefix = cmStrCat(this->Name, "_FIND_VERSION"_s);
  1110. this->SetVersionVariables(addDefinition, prefix, this->Version,
  1111. this->VersionCount, this->VersionMajor,
  1112. this->VersionMinor, this->VersionPatch,
  1113. this->VersionTweak);
  1114. // Tell the module whether an exact version has been requested.
  1115. auto exact = cmStrCat(this->Name, "_FIND_VERSION_EXACT");
  1116. this->AddFindDefinition(exact, this->VersionExact ? "1"_s : "0"_s);
  1117. }
  1118. if (!this->VersionRange.empty()) {
  1119. auto prefix = cmStrCat(this->Name, "_FIND_VERSION_MIN"_s);
  1120. this->SetVersionVariables(addDefinition, prefix, this->Version,
  1121. this->VersionCount, this->VersionMajor,
  1122. this->VersionMinor, this->VersionPatch,
  1123. this->VersionTweak);
  1124. prefix = cmStrCat(this->Name, "_FIND_VERSION_MAX"_s);
  1125. this->SetVersionVariables(addDefinition, prefix, this->VersionMax,
  1126. this->VersionMaxCount, this->VersionMaxMajor,
  1127. this->VersionMaxMinor, this->VersionMaxPatch,
  1128. this->VersionMaxTweak);
  1129. auto id = cmStrCat(this->Name, "_FIND_VERSION_RANGE");
  1130. this->AddFindDefinition(id, this->VersionRange);
  1131. id = cmStrCat(this->Name, "_FIND_VERSION_RANGE_MIN");
  1132. this->AddFindDefinition(id, this->VersionRangeMin);
  1133. id = cmStrCat(this->Name, "_FIND_VERSION_RANGE_MAX");
  1134. this->AddFindDefinition(id, this->VersionRangeMax);
  1135. }
  1136. if (this->RegistryViewDefined) {
  1137. this->AddFindDefinition(cmStrCat(this->Name, "_FIND_REGISTRY_VIEW"),
  1138. cmWindowsRegistry::FromView(this->RegistryView));
  1139. }
  1140. }
  1141. void cmFindPackageCommand::AddFindDefinition(const std::string& var,
  1142. const cm::string_view value)
  1143. {
  1144. if (cmValue old = this->Makefile->GetDefinition(var)) {
  1145. this->OriginalDefs[var].exists = true;
  1146. this->OriginalDefs[var].value = *old;
  1147. } else {
  1148. this->OriginalDefs[var].exists = false;
  1149. }
  1150. this->Makefile->AddDefinition(var, value);
  1151. }
  1152. void cmFindPackageCommand::RestoreFindDefinitions()
  1153. {
  1154. for (auto const& i : this->OriginalDefs) {
  1155. OriginalDef const& od = i.second;
  1156. if (od.exists) {
  1157. this->Makefile->AddDefinition(i.first, od.value);
  1158. } else {
  1159. this->Makefile->RemoveDefinition(i.first);
  1160. }
  1161. }
  1162. }
  1163. bool cmFindPackageCommand::FindModule(bool& found)
  1164. {
  1165. std::string moduleFileName = cmStrCat("Find", this->Name, ".cmake");
  1166. bool system = false;
  1167. std::string debugBuffer = cmStrCat(
  1168. "find_package considered the following paths for ", moduleFileName, ":\n");
  1169. std::string mfile = this->Makefile->GetModulesFile(
  1170. moduleFileName, system, this->DebugMode, debugBuffer);
  1171. if (this->DebugMode) {
  1172. if (mfile.empty()) {
  1173. debugBuffer = cmStrCat(debugBuffer, "The file was not found.\n");
  1174. } else {
  1175. debugBuffer =
  1176. cmStrCat(debugBuffer, "The file was found at\n ", mfile, "\n");
  1177. }
  1178. this->DebugBuffer = cmStrCat(this->DebugBuffer, debugBuffer);
  1179. }
  1180. if (!mfile.empty()) {
  1181. if (system) {
  1182. auto const it = this->DeprecatedFindModules.find(this->Name);
  1183. if (it != this->DeprecatedFindModules.end()) {
  1184. cmPolicies::PolicyStatus status =
  1185. this->Makefile->GetPolicyStatus(it->second);
  1186. switch (status) {
  1187. case cmPolicies::WARN: {
  1188. this->Makefile->IssueMessage(
  1189. MessageType::AUTHOR_WARNING,
  1190. cmStrCat(cmPolicies::GetPolicyWarning(it->second), "\n"));
  1191. CM_FALLTHROUGH;
  1192. }
  1193. case cmPolicies::OLD:
  1194. break;
  1195. case cmPolicies::REQUIRED_IF_USED:
  1196. case cmPolicies::REQUIRED_ALWAYS:
  1197. case cmPolicies::NEW:
  1198. return true;
  1199. }
  1200. }
  1201. }
  1202. // Load the module we found, and set "<name>_FIND_MODULE" to true
  1203. // while inside it.
  1204. found = true;
  1205. std::string const var = cmStrCat(this->Name, "_FIND_MODULE");
  1206. this->Makefile->AddDefinition(var, "1");
  1207. bool result = this->ReadListFile(mfile, DoPolicyScope);
  1208. this->Makefile->RemoveDefinition(var);
  1209. if (this->DebugMode) {
  1210. std::string const foundVar = cmStrCat(this->Name, "_FOUND");
  1211. if (this->Makefile->IsDefinitionSet(foundVar) &&
  1212. !this->Makefile->IsOn(foundVar)) {
  1213. this->DebugBuffer = cmStrCat(
  1214. this->DebugBuffer, "The module is considered not found due to ",
  1215. foundVar, " being FALSE.");
  1216. }
  1217. }
  1218. return result;
  1219. }
  1220. return true;
  1221. }
  1222. bool cmFindPackageCommand::HandlePackageMode(
  1223. const HandlePackageModeType handlePackageModeType)
  1224. {
  1225. this->ConsideredConfigs.clear();
  1226. // Try to find the config file.
  1227. cmValue def = this->Makefile->GetDefinition(this->Variable);
  1228. // Try to load the config file if the directory is known
  1229. bool fileFound = false;
  1230. if (this->UseConfigFiles) {
  1231. if (!cmIsOff(def)) {
  1232. // Get the directory from the variable value.
  1233. std::string dir = *def;
  1234. cmSystemTools::ConvertToUnixSlashes(dir);
  1235. // Treat relative paths with respect to the current source dir.
  1236. if (!cmSystemTools::FileIsFullPath(dir)) {
  1237. dir = "/" + dir;
  1238. dir = this->Makefile->GetCurrentSourceDirectory() + dir;
  1239. }
  1240. // The file location was cached. Look for the correct file.
  1241. std::string file;
  1242. if (this->FindConfigFile(dir, file)) {
  1243. this->FileFound = file;
  1244. fileFound = true;
  1245. }
  1246. def = this->Makefile->GetDefinition(this->Variable);
  1247. }
  1248. // Search for the config file if it is not already found.
  1249. if (cmIsOff(def) || !fileFound) {
  1250. fileFound = this->FindConfig();
  1251. }
  1252. // Sanity check.
  1253. if (fileFound && this->FileFound.empty()) {
  1254. this->Makefile->IssueMessage(
  1255. MessageType::INTERNAL_ERROR,
  1256. "fileFound is true but FileFound is empty!");
  1257. fileFound = false;
  1258. }
  1259. }
  1260. std::string const foundVar = cmStrCat(this->Name, "_FOUND");
  1261. std::string const notFoundMessageVar =
  1262. cmStrCat(this->Name, "_NOT_FOUND_MESSAGE");
  1263. std::string notFoundMessage;
  1264. // If the directory for the config file was found, try to read the file.
  1265. bool result = true;
  1266. bool found = false;
  1267. bool configFileSetFOUNDFalse = false;
  1268. if (fileFound) {
  1269. if (this->Makefile->IsDefinitionSet(foundVar) &&
  1270. !this->Makefile->IsOn(foundVar)) {
  1271. // by removing Foo_FOUND here if it is FALSE, we don't really change
  1272. // the situation for the Config file which is about to be included,
  1273. // but we make it possible to detect later on whether the Config file
  1274. // has set Foo_FOUND to FALSE itself:
  1275. this->Makefile->RemoveDefinition(foundVar);
  1276. }
  1277. this->Makefile->RemoveDefinition(notFoundMessageVar);
  1278. // Set the version variables before loading the config file.
  1279. // It may override them.
  1280. this->StoreVersionFound();
  1281. // Parse the configuration file.
  1282. if (this->ReadListFile(this->FileFound, DoPolicyScope)) {
  1283. // The package has been found.
  1284. found = true;
  1285. // Check whether the Config file has set Foo_FOUND to FALSE:
  1286. if (this->Makefile->IsDefinitionSet(foundVar) &&
  1287. !this->Makefile->IsOn(foundVar)) {
  1288. // we get here if the Config file has set Foo_FOUND actively to FALSE
  1289. found = false;
  1290. configFileSetFOUNDFalse = true;
  1291. notFoundMessage =
  1292. this->Makefile->GetSafeDefinition(notFoundMessageVar);
  1293. }
  1294. } else {
  1295. // The configuration file is invalid.
  1296. result = false;
  1297. }
  1298. }
  1299. if (this->UseFindModules && !found &&
  1300. handlePackageModeType == HandlePackageModeType::Config &&
  1301. this->Makefile->IsOn("CMAKE_FIND_PACKAGE_PREFER_CONFIG")) {
  1302. // Config mode failed. Allow Module case.
  1303. result = false;
  1304. }
  1305. // package not found
  1306. if (result && !found) {
  1307. // warn if package required or neither quiet nor in config mode
  1308. if (this->Required ||
  1309. !(this->Quiet ||
  1310. (this->UseConfigFiles && !this->UseFindModules &&
  1311. this->ConsideredConfigs.empty()))) {
  1312. // The variable is not set.
  1313. std::ostringstream e;
  1314. std::ostringstream aw;
  1315. if (configFileSetFOUNDFalse) {
  1316. /* clang-format off */
  1317. e << "Found package configuration file:\n"
  1318. " " << this->FileFound << "\n"
  1319. "but it set " << foundVar << " to FALSE so package \"" <<
  1320. this->Name << "\" is considered to be NOT FOUND.";
  1321. /* clang-format on */
  1322. if (!notFoundMessage.empty()) {
  1323. e << " Reason given by package: \n" << notFoundMessage << "\n";
  1324. }
  1325. }
  1326. // If there are files in ConsideredConfigs, it means that FooConfig.cmake
  1327. // have been found, but they didn't have appropriate versions.
  1328. else if (!this->ConsideredConfigs.empty()) {
  1329. auto duplicate_end = cmRemoveDuplicates(this->ConsideredConfigs);
  1330. e << "Could not find a configuration file for package \"" << this->Name
  1331. << "\" that "
  1332. << (this->VersionExact ? "exactly matches" : "is compatible with")
  1333. << " requested version "
  1334. << (this->VersionRange.empty() ? "" : "range ") << "\""
  1335. << this->VersionComplete
  1336. << "\".\n"
  1337. "The following configuration files were considered but not "
  1338. "accepted:\n";
  1339. for (ConfigFileInfo const& info :
  1340. cmMakeRange(this->ConsideredConfigs.cbegin(), duplicate_end)) {
  1341. e << " " << info.filename << ", version: " << info.version << "\n";
  1342. }
  1343. } else {
  1344. std::string requestedVersionString;
  1345. if (!this->VersionComplete.empty()) {
  1346. requestedVersionString =
  1347. cmStrCat(" (requested version ", this->VersionComplete, ')');
  1348. }
  1349. if (this->UseConfigFiles) {
  1350. if (this->UseFindModules) {
  1351. e << "By not providing \"Find" << this->Name
  1352. << ".cmake\" in "
  1353. "CMAKE_MODULE_PATH this project has asked CMake to find a "
  1354. "package configuration file provided by \""
  1355. << this->Name
  1356. << "\", "
  1357. "but CMake did not find one.\n";
  1358. }
  1359. if (this->Configs.size() == 1) {
  1360. e << "Could not find a package configuration file named \""
  1361. << this->Configs[0] << "\" provided by package \"" << this->Name
  1362. << "\"" << requestedVersionString << ".\n";
  1363. } else {
  1364. e << "Could not find a package configuration file provided by \""
  1365. << this->Name << "\"" << requestedVersionString
  1366. << " with any of the following names:\n"
  1367. << cmWrap(" ", this->Configs, "", "\n") << "\n";
  1368. }
  1369. e << "Add the installation prefix of \"" << this->Name
  1370. << "\" to "
  1371. "CMAKE_PREFIX_PATH or set \""
  1372. << this->Variable
  1373. << "\" to a "
  1374. "directory containing one of the above files. "
  1375. "If \""
  1376. << this->Name
  1377. << "\" provides a separate development "
  1378. "package or SDK, be sure it has been installed.";
  1379. } else // if(!this->UseFindModules && !this->UseConfigFiles)
  1380. {
  1381. e << "No \"Find" << this->Name
  1382. << ".cmake\" found in "
  1383. "CMAKE_MODULE_PATH.";
  1384. aw
  1385. << "Find" << this->Name
  1386. << ".cmake must either be part of this "
  1387. "project itself, in this case adjust CMAKE_MODULE_PATH so that "
  1388. "it points to the correct location inside its source tree.\n"
  1389. "Or it must be installed by a package which has already been "
  1390. "found via find_package(). In this case make sure that "
  1391. "package has indeed been found and adjust CMAKE_MODULE_PATH to "
  1392. "contain the location where that package has installed "
  1393. "Find"
  1394. << this->Name
  1395. << ".cmake. This must be a location "
  1396. "provided by that package. This error in general means that "
  1397. "the buildsystem of this project is relying on a Find-module "
  1398. "without ensuring that it is actually available.\n";
  1399. }
  1400. }
  1401. this->Makefile->IssueMessage(this->Required ? MessageType::FATAL_ERROR
  1402. : MessageType::WARNING,
  1403. e.str());
  1404. if (this->Required) {
  1405. cmSystemTools::SetFatalErrorOccurred();
  1406. }
  1407. if (!aw.str().empty()) {
  1408. this->Makefile->IssueMessage(MessageType::AUTHOR_WARNING, aw.str());
  1409. }
  1410. }
  1411. // output result if in config mode but not in quiet mode
  1412. else if (!this->Quiet) {
  1413. this->Makefile->DisplayStatus(cmStrCat("Could NOT find ", this->Name,
  1414. " (missing: ", this->Name,
  1415. "_DIR)"),
  1416. -1);
  1417. }
  1418. }
  1419. // Set a variable marking whether the package was found.
  1420. this->Makefile->AddDefinition(foundVar, found ? "1" : "0");
  1421. // Set a variable naming the configuration file that was found.
  1422. std::string const fileVar = cmStrCat(this->Name, "_CONFIG");
  1423. if (found) {
  1424. this->Makefile->AddDefinition(fileVar, this->FileFound);
  1425. } else {
  1426. this->Makefile->RemoveDefinition(fileVar);
  1427. }
  1428. std::string const consideredConfigsVar =
  1429. cmStrCat(this->Name, "_CONSIDERED_CONFIGS");
  1430. std::string const consideredVersionsVar =
  1431. cmStrCat(this->Name, "_CONSIDERED_VERSIONS");
  1432. std::string consideredConfigFiles;
  1433. std::string consideredVersions;
  1434. const char* sep = "";
  1435. for (ConfigFileInfo const& i : this->ConsideredConfigs) {
  1436. consideredConfigFiles += sep;
  1437. consideredVersions += sep;
  1438. consideredConfigFiles += i.filename;
  1439. consideredVersions += i.version;
  1440. sep = ";";
  1441. }
  1442. this->Makefile->AddDefinition(consideredConfigsVar, consideredConfigFiles);
  1443. this->Makefile->AddDefinition(consideredVersionsVar, consideredVersions);
  1444. return result;
  1445. }
  1446. bool cmFindPackageCommand::FindConfig()
  1447. {
  1448. // Compute the set of search prefixes.
  1449. this->ComputePrefixes();
  1450. // Look for the project's configuration file.
  1451. bool found = false;
  1452. if (this->DebugMode) {
  1453. this->DebugBuffer = cmStrCat(this->DebugBuffer,
  1454. "find_package considered the following "
  1455. "locations for ",
  1456. this->Name, "'s Config module:\n");
  1457. }
  1458. // Search for frameworks.
  1459. if (!found && (this->SearchFrameworkFirst || this->SearchFrameworkOnly)) {
  1460. found = this->FindFrameworkConfig();
  1461. }
  1462. // Search for apps.
  1463. if (!found && (this->SearchAppBundleFirst || this->SearchAppBundleOnly)) {
  1464. found = this->FindAppBundleConfig();
  1465. }
  1466. // Search prefixes.
  1467. if (!found && !(this->SearchFrameworkOnly || this->SearchAppBundleOnly)) {
  1468. found = this->FindPrefixedConfig();
  1469. }
  1470. // Search for frameworks.
  1471. if (!found && this->SearchFrameworkLast) {
  1472. found = this->FindFrameworkConfig();
  1473. }
  1474. // Search for apps.
  1475. if (!found && this->SearchAppBundleLast) {
  1476. found = this->FindAppBundleConfig();
  1477. }
  1478. if (this->DebugMode) {
  1479. if (found) {
  1480. this->DebugBuffer = cmStrCat(
  1481. this->DebugBuffer, "The file was found at\n ", this->FileFound, "\n");
  1482. } else {
  1483. this->DebugBuffer =
  1484. cmStrCat(this->DebugBuffer, "The file was not found.\n");
  1485. }
  1486. }
  1487. // Store the entry in the cache so it can be set by the user.
  1488. std::string init;
  1489. if (found) {
  1490. init = cmSystemTools::GetFilenamePath(this->FileFound);
  1491. } else {
  1492. init = this->Variable + "-NOTFOUND";
  1493. }
  1494. // We force the value since we do not get here if it was already set.
  1495. this->SetConfigDirCacheVariable(init);
  1496. return found;
  1497. }
  1498. void cmFindPackageCommand::SetConfigDirCacheVariable(const std::string& value)
  1499. {
  1500. std::string const help =
  1501. cmStrCat("The directory containing a CMake configuration file for ",
  1502. this->Name, '.');
  1503. this->Makefile->AddCacheDefinition(this->Variable, value, help.c_str(),
  1504. cmStateEnums::PATH, true);
  1505. if (this->Makefile->GetPolicyStatus(cmPolicies::CMP0126) ==
  1506. cmPolicies::NEW &&
  1507. this->Makefile->IsNormalDefinitionSet(this->Variable)) {
  1508. this->Makefile->AddDefinition(this->Variable, value);
  1509. }
  1510. }
  1511. bool cmFindPackageCommand::FindPrefixedConfig()
  1512. {
  1513. std::vector<std::string> const& prefixes = this->SearchPaths;
  1514. return std::any_of(
  1515. prefixes.begin(), prefixes.end(),
  1516. [this](std::string const& p) -> bool { return this->SearchPrefix(p); });
  1517. }
  1518. bool cmFindPackageCommand::FindFrameworkConfig()
  1519. {
  1520. std::vector<std::string> const& prefixes = this->SearchPaths;
  1521. return std::any_of(prefixes.begin(), prefixes.end(),
  1522. [this](std::string const& p) -> bool {
  1523. return this->SearchFrameworkPrefix(p);
  1524. });
  1525. }
  1526. bool cmFindPackageCommand::FindAppBundleConfig()
  1527. {
  1528. std::vector<std::string> const& prefixes = this->SearchPaths;
  1529. return std::any_of(prefixes.begin(), prefixes.end(),
  1530. [this](std::string const& p) -> bool {
  1531. return this->SearchAppBundlePrefix(p);
  1532. });
  1533. }
  1534. bool cmFindPackageCommand::ReadListFile(const std::string& f,
  1535. const PolicyScopeRule psr)
  1536. {
  1537. const bool noPolicyScope = !this->PolicyScope || psr == NoPolicyScope;
  1538. using ITScope = cmMakefile::ImportedTargetScope;
  1539. ITScope scope = this->GlobalScope ? ITScope::Global : ITScope::Local;
  1540. cmMakefile::SetGlobalTargetImportScope globScope(this->Makefile, scope);
  1541. if (this->Makefile->ReadDependentFile(f, noPolicyScope)) {
  1542. return true;
  1543. }
  1544. std::string const e = cmStrCat("Error reading CMake code from \"", f, "\".");
  1545. this->SetError(e);
  1546. return false;
  1547. }
  1548. void cmFindPackageCommand::AppendToFoundProperty(const bool found)
  1549. {
  1550. std::vector<std::string> foundContents;
  1551. cmValue foundProp =
  1552. this->Makefile->GetState()->GetGlobalProperty("PACKAGES_FOUND");
  1553. if (cmNonempty(foundProp)) {
  1554. cmExpandList(*foundProp, foundContents, false);
  1555. auto nameIt =
  1556. std::find(foundContents.begin(), foundContents.end(), this->Name);
  1557. if (nameIt != foundContents.end()) {
  1558. foundContents.erase(nameIt);
  1559. }
  1560. }
  1561. std::vector<std::string> notFoundContents;
  1562. cmValue notFoundProp =
  1563. this->Makefile->GetState()->GetGlobalProperty("PACKAGES_NOT_FOUND");
  1564. if (cmNonempty(notFoundProp)) {
  1565. cmExpandList(*notFoundProp, notFoundContents, false);
  1566. auto nameIt =
  1567. std::find(notFoundContents.begin(), notFoundContents.end(), this->Name);
  1568. if (nameIt != notFoundContents.end()) {
  1569. notFoundContents.erase(nameIt);
  1570. }
  1571. }
  1572. if (found) {
  1573. foundContents.push_back(this->Name);
  1574. } else {
  1575. notFoundContents.push_back(this->Name);
  1576. }
  1577. std::string tmp = cmJoin(foundContents, ";");
  1578. this->Makefile->GetState()->SetGlobalProperty("PACKAGES_FOUND", tmp.c_str());
  1579. tmp = cmJoin(notFoundContents, ";");
  1580. this->Makefile->GetState()->SetGlobalProperty("PACKAGES_NOT_FOUND",
  1581. tmp.c_str());
  1582. }
  1583. void cmFindPackageCommand::AppendSuccessInformation()
  1584. {
  1585. {
  1586. std::string const transitivePropName =
  1587. cmStrCat("_CMAKE_", this->Name, "_TRANSITIVE_DEPENDENCY");
  1588. this->Makefile->GetState()->SetGlobalProperty(transitivePropName, "False");
  1589. }
  1590. std::string const found = cmStrCat(this->Name, "_FOUND");
  1591. std::string const upperFound = cmSystemTools::UpperCase(found);
  1592. bool const upperResult = this->Makefile->IsOn(upperFound);
  1593. bool const result = this->Makefile->IsOn(found);
  1594. bool const packageFound = (result || upperResult);
  1595. this->AppendToFoundProperty(packageFound);
  1596. // Record whether the find was quiet or not, so this can be used
  1597. // e.g. in FeatureSummary.cmake
  1598. std::string const quietInfoPropName =
  1599. cmStrCat("_CMAKE_", this->Name, "_QUIET");
  1600. this->Makefile->GetState()->SetGlobalProperty(
  1601. quietInfoPropName, this->Quiet ? "TRUE" : "FALSE");
  1602. // set a global property to record the required version of this package
  1603. std::string const versionInfoPropName =
  1604. cmStrCat("_CMAKE_", this->Name, "_REQUIRED_VERSION");
  1605. std::string versionInfo;
  1606. if (!this->VersionRange.empty()) {
  1607. versionInfo = this->VersionRange;
  1608. } else if (!this->Version.empty()) {
  1609. versionInfo =
  1610. cmStrCat(this->VersionExact ? "==" : ">=", ' ', this->Version);
  1611. }
  1612. this->Makefile->GetState()->SetGlobalProperty(versionInfoPropName,
  1613. versionInfo.c_str());
  1614. if (this->Required) {
  1615. std::string const requiredInfoPropName =
  1616. cmStrCat("_CMAKE_", this->Name, "_TYPE");
  1617. this->Makefile->GetState()->SetGlobalProperty(requiredInfoPropName,
  1618. "REQUIRED");
  1619. }
  1620. }
  1621. void cmFindPackageCommand::ComputePrefixes()
  1622. {
  1623. this->FillPrefixesPackageRedirect();
  1624. if (!this->NoDefaultPath) {
  1625. if (!this->NoPackageRootPath) {
  1626. this->FillPrefixesPackageRoot();
  1627. }
  1628. if (!this->NoCMakePath) {
  1629. this->FillPrefixesCMakeVariable();
  1630. }
  1631. if (!this->NoCMakeEnvironmentPath) {
  1632. this->FillPrefixesCMakeEnvironment();
  1633. }
  1634. }
  1635. this->FillPrefixesUserHints();
  1636. if (!this->NoDefaultPath) {
  1637. if (!this->NoSystemEnvironmentPath) {
  1638. this->FillPrefixesSystemEnvironment();
  1639. }
  1640. if (!this->NoUserRegistry) {
  1641. this->FillPrefixesUserRegistry();
  1642. }
  1643. if (!this->NoCMakeSystemPath) {
  1644. this->FillPrefixesCMakeSystemVariable();
  1645. }
  1646. if (!this->NoSystemRegistry) {
  1647. this->FillPrefixesSystemRegistry();
  1648. }
  1649. }
  1650. this->FillPrefixesUserGuess();
  1651. this->ComputeFinalPaths(IgnorePaths::No);
  1652. }
  1653. void cmFindPackageCommand::FillPrefixesPackageRedirect()
  1654. {
  1655. cmSearchPath& paths = this->LabeledPaths[PathLabel::PackageRedirect];
  1656. const auto redirectDir =
  1657. this->Makefile->GetDefinition("CMAKE_FIND_PACKAGE_REDIRECTS_DIR");
  1658. if (redirectDir && !redirectDir->empty()) {
  1659. paths.AddPath(*redirectDir);
  1660. }
  1661. if (this->DebugMode) {
  1662. std::string debugBuffer =
  1663. "The internally managed CMAKE_FIND_PACKAGE_REDIRECTS_DIR.\n";
  1664. collectPathsForDebug(debugBuffer, paths);
  1665. this->DebugBuffer = cmStrCat(this->DebugBuffer, debugBuffer);
  1666. }
  1667. }
  1668. void cmFindPackageCommand::FillPrefixesPackageRoot()
  1669. {
  1670. cmSearchPath& paths = this->LabeledPaths[PathLabel::PackageRoot];
  1671. // Add the PACKAGE_ROOT_PATH from each enclosing find_package call.
  1672. for (auto pkgPaths = this->Makefile->FindPackageRootPathStack.rbegin();
  1673. pkgPaths != this->Makefile->FindPackageRootPathStack.rend();
  1674. ++pkgPaths) {
  1675. for (std::string const& path : *pkgPaths) {
  1676. paths.AddPath(path);
  1677. }
  1678. }
  1679. if (this->DebugMode) {
  1680. std::string debugBuffer = "<PackageName>_ROOT CMake variable "
  1681. "[CMAKE_FIND_USE_PACKAGE_ROOT_PATH].\n";
  1682. collectPathsForDebug(debugBuffer, paths);
  1683. this->DebugBuffer = cmStrCat(this->DebugBuffer, debugBuffer);
  1684. }
  1685. }
  1686. void cmFindPackageCommand::FillPrefixesCMakeEnvironment()
  1687. {
  1688. cmSearchPath& paths = this->LabeledPaths[PathLabel::CMakeEnvironment];
  1689. std::string debugBuffer;
  1690. std::size_t debugOffset = 0;
  1691. // Check the environment variable with the same name as the cache
  1692. // entry.
  1693. paths.AddEnvPath(this->Variable);
  1694. if (this->DebugMode) {
  1695. debugBuffer = cmStrCat("Env variable ", this->Variable,
  1696. " [CMAKE_FIND_USE_CMAKE_ENVIRONMENT_PATH].\n");
  1697. debugOffset = collectPathsForDebug(debugBuffer, paths);
  1698. }
  1699. // And now the general CMake environment variables
  1700. paths.AddEnvPath("CMAKE_PREFIX_PATH");
  1701. if (this->DebugMode) {
  1702. debugBuffer = cmStrCat(debugBuffer,
  1703. "CMAKE_PREFIX_PATH env variable "
  1704. "[CMAKE_FIND_USE_CMAKE_ENVIRONMENT_PATH].\n");
  1705. debugOffset = collectPathsForDebug(debugBuffer, paths, debugOffset);
  1706. }
  1707. paths.AddEnvPath("CMAKE_FRAMEWORK_PATH");
  1708. paths.AddEnvPath("CMAKE_APPBUNDLE_PATH");
  1709. if (this->DebugMode) {
  1710. debugBuffer =
  1711. cmStrCat(debugBuffer,
  1712. "CMAKE_FRAMEWORK_PATH and CMAKE_APPBUNDLE_PATH env "
  1713. "variables [CMAKE_FIND_USE_CMAKE_ENVIRONMENT_PATH].\n");
  1714. collectPathsForDebug(debugBuffer, paths, debugOffset);
  1715. this->DebugBuffer = cmStrCat(this->DebugBuffer, debugBuffer);
  1716. }
  1717. }
  1718. void cmFindPackageCommand::FillPrefixesCMakeVariable()
  1719. {
  1720. cmSearchPath& paths = this->LabeledPaths[PathLabel::CMake];
  1721. std::string debugBuffer;
  1722. std::size_t debugOffset = 0;
  1723. paths.AddCMakePath("CMAKE_PREFIX_PATH");
  1724. if (this->DebugMode) {
  1725. debugBuffer = "CMAKE_PREFIX_PATH variable [CMAKE_FIND_USE_CMAKE_PATH].\n";
  1726. debugOffset = collectPathsForDebug(debugBuffer, paths);
  1727. }
  1728. paths.AddCMakePath("CMAKE_FRAMEWORK_PATH");
  1729. paths.AddCMakePath("CMAKE_APPBUNDLE_PATH");
  1730. if (this->DebugMode) {
  1731. debugBuffer =
  1732. cmStrCat(debugBuffer,
  1733. "CMAKE_FRAMEWORK_PATH and CMAKE_APPBUNDLE_PATH variables "
  1734. "[CMAKE_FIND_USE_CMAKE_PATH].\n");
  1735. collectPathsForDebug(debugBuffer, paths, debugOffset);
  1736. this->DebugBuffer = cmStrCat(this->DebugBuffer, debugBuffer);
  1737. }
  1738. }
  1739. void cmFindPackageCommand::FillPrefixesSystemEnvironment()
  1740. {
  1741. cmSearchPath& paths = this->LabeledPaths[PathLabel::SystemEnvironment];
  1742. // Use the system search path to generate prefixes.
  1743. // Relative paths are interpreted with respect to the current
  1744. // working directory.
  1745. std::vector<std::string> tmp;
  1746. cmSystemTools::GetPath(tmp);
  1747. for (std::string const& i : tmp) {
  1748. // If the path is a PREFIX/bin case then add its parent instead.
  1749. if ((cmHasLiteralSuffix(i, "/bin")) || (cmHasLiteralSuffix(i, "/sbin"))) {
  1750. paths.AddPath(cmSystemTools::GetFilenamePath(i));
  1751. } else {
  1752. paths.AddPath(i);
  1753. }
  1754. }
  1755. if (this->DebugMode) {
  1756. std::string debugBuffer = "Standard system environment variables "
  1757. "[CMAKE_FIND_USE_SYSTEM_ENVIRONMENT_PATH].\n";
  1758. collectPathsForDebug(debugBuffer, paths);
  1759. this->DebugBuffer = cmStrCat(this->DebugBuffer, debugBuffer);
  1760. }
  1761. }
  1762. void cmFindPackageCommand::FillPrefixesUserRegistry()
  1763. {
  1764. #if defined(_WIN32) && !defined(__CYGWIN__)
  1765. this->LoadPackageRegistryWinUser();
  1766. #elif defined(__HAIKU__)
  1767. char dir[B_PATH_NAME_LENGTH];
  1768. if (find_directory(B_USER_SETTINGS_DIRECTORY, -1, false, dir, sizeof(dir)) ==
  1769. B_OK) {
  1770. std::string fname = cmStrCat(dir, "/cmake/packages/", Name);
  1771. this->LoadPackageRegistryDir(fname,
  1772. this->LabeledPaths[PathLabel::UserRegistry]);
  1773. }
  1774. #else
  1775. std::string dir;
  1776. if (cmSystemTools::GetEnv("HOME", dir)) {
  1777. dir += "/.cmake/packages/";
  1778. dir += this->Name;
  1779. this->LoadPackageRegistryDir(dir,
  1780. this->LabeledPaths[PathLabel::UserRegistry]);
  1781. }
  1782. #endif
  1783. if (this->DebugMode) {
  1784. std::string debugBuffer =
  1785. "CMake User Package Registry [CMAKE_FIND_USE_PACKAGE_REGISTRY].\n";
  1786. collectPathsForDebug(debugBuffer,
  1787. this->LabeledPaths[PathLabel::UserRegistry]);
  1788. this->DebugBuffer = cmStrCat(this->DebugBuffer, debugBuffer);
  1789. }
  1790. }
  1791. void cmFindPackageCommand::FillPrefixesSystemRegistry()
  1792. {
  1793. if (this->NoSystemRegistry || this->NoDefaultPath) {
  1794. return;
  1795. }
  1796. #if defined(_WIN32) && !defined(__CYGWIN__)
  1797. this->LoadPackageRegistryWinSystem();
  1798. #endif
  1799. if (this->DebugMode) {
  1800. std::string debugBuffer =
  1801. "CMake System Package Registry "
  1802. "[CMAKE_FIND_PACKAGE_NO_SYSTEM_PACKAGE_REGISTRY].\n";
  1803. collectPathsForDebug(debugBuffer,
  1804. this->LabeledPaths[PathLabel::SystemRegistry]);
  1805. this->DebugBuffer = cmStrCat(this->DebugBuffer, debugBuffer);
  1806. }
  1807. }
  1808. #if defined(_WIN32) && !defined(__CYGWIN__)
  1809. void cmFindPackageCommand::LoadPackageRegistryWinUser()
  1810. {
  1811. // HKEY_CURRENT_USER\\Software shares 32-bit and 64-bit views.
  1812. this->LoadPackageRegistryWin(true, 0,
  1813. this->LabeledPaths[PathLabel::UserRegistry]);
  1814. }
  1815. void cmFindPackageCommand::LoadPackageRegistryWinSystem()
  1816. {
  1817. cmSearchPath& paths = this->LabeledPaths[PathLabel::SystemRegistry];
  1818. // HKEY_LOCAL_MACHINE\\SOFTWARE has separate 32-bit and 64-bit views.
  1819. // Prefer the target platform view first.
  1820. if (this->Makefile->PlatformIs64Bit()) {
  1821. this->LoadPackageRegistryWin(false, KEY_WOW64_64KEY, paths);
  1822. this->LoadPackageRegistryWin(false, KEY_WOW64_32KEY, paths);
  1823. } else {
  1824. this->LoadPackageRegistryWin(false, KEY_WOW64_32KEY, paths);
  1825. this->LoadPackageRegistryWin(false, KEY_WOW64_64KEY, paths);
  1826. }
  1827. }
  1828. void cmFindPackageCommand::LoadPackageRegistryWin(const bool user,
  1829. const unsigned int view,
  1830. cmSearchPath& outPaths)
  1831. {
  1832. std::wstring key = L"Software\\Kitware\\CMake\\Packages\\";
  1833. key += cmsys::Encoding::ToWide(this->Name);
  1834. std::set<std::wstring> bad;
  1835. HKEY hKey;
  1836. if (RegOpenKeyExW(user ? HKEY_CURRENT_USER : HKEY_LOCAL_MACHINE, key.c_str(),
  1837. 0, KEY_QUERY_VALUE | view, &hKey) == ERROR_SUCCESS) {
  1838. DWORD valueType = REG_NONE;
  1839. wchar_t name[16383]; // RegEnumValue docs limit name to 32767 _bytes_
  1840. std::vector<wchar_t> data(512);
  1841. bool done = false;
  1842. DWORD index = 0;
  1843. while (!done) {
  1844. DWORD nameSize = static_cast<DWORD>(sizeof(name));
  1845. DWORD dataSize = static_cast<DWORD>(data.size() * sizeof(data[0]));
  1846. switch (RegEnumValueW(hKey, index, name, &nameSize, 0, &valueType,
  1847. (BYTE*)&data[0], &dataSize)) {
  1848. case ERROR_SUCCESS:
  1849. ++index;
  1850. if (valueType == REG_SZ) {
  1851. data[dataSize] = 0;
  1852. if (!this->CheckPackageRegistryEntry(
  1853. cmsys::Encoding::ToNarrow(&data[0]), outPaths)) {
  1854. // The entry is invalid.
  1855. bad.insert(name);
  1856. }
  1857. }
  1858. break;
  1859. case ERROR_MORE_DATA:
  1860. data.resize((dataSize + sizeof(data[0]) - 1) / sizeof(data[0]));
  1861. break;
  1862. case ERROR_NO_MORE_ITEMS:
  1863. default:
  1864. done = true;
  1865. break;
  1866. }
  1867. }
  1868. RegCloseKey(hKey);
  1869. }
  1870. // Remove bad values if possible.
  1871. if (user && !bad.empty() &&
  1872. RegOpenKeyExW(HKEY_CURRENT_USER, key.c_str(), 0, KEY_SET_VALUE | view,
  1873. &hKey) == ERROR_SUCCESS) {
  1874. for (std::wstring const& v : bad) {
  1875. RegDeleteValueW(hKey, v.c_str());
  1876. }
  1877. RegCloseKey(hKey);
  1878. }
  1879. }
  1880. #else
  1881. void cmFindPackageCommand::LoadPackageRegistryDir(std::string const& dir,
  1882. cmSearchPath& outPaths)
  1883. {
  1884. cmsys::Directory files;
  1885. if (!files.Load(dir)) {
  1886. return;
  1887. }
  1888. std::string fname;
  1889. for (unsigned long i = 0; i < files.GetNumberOfFiles(); ++i) {
  1890. fname = cmStrCat(dir, '/', files.GetFile(i));
  1891. if (!cmSystemTools::FileIsDirectory(fname)) {
  1892. // Hold this file hostage until it behaves.
  1893. cmFindPackageCommandHoldFile holdFile(fname.c_str());
  1894. // Load the file.
  1895. cmsys::ifstream fin(fname.c_str(), std::ios::in | std::ios::binary);
  1896. std::string fentry;
  1897. if (fin && cmSystemTools::GetLineFromStream(fin, fentry) &&
  1898. this->CheckPackageRegistryEntry(fentry, outPaths)) {
  1899. // The file references an existing package, so release it.
  1900. holdFile.Release();
  1901. }
  1902. }
  1903. }
  1904. // TODO: Wipe out the directory if it is empty.
  1905. }
  1906. #endif
  1907. bool cmFindPackageCommand::CheckPackageRegistryEntry(const std::string& fname,
  1908. cmSearchPath& outPaths)
  1909. {
  1910. // Parse the content of one package registry entry.
  1911. if (cmSystemTools::FileIsFullPath(fname)) {
  1912. // The first line in the stream is the full path to a file or
  1913. // directory containing the package.
  1914. if (cmSystemTools::FileExists(fname)) {
  1915. // The path exists. Look for the package here.
  1916. if (!cmSystemTools::FileIsDirectory(fname)) {
  1917. outPaths.AddPath(cmSystemTools::GetFilenamePath(fname));
  1918. } else {
  1919. outPaths.AddPath(fname);
  1920. }
  1921. return true;
  1922. }
  1923. // The path does not exist. Assume the stream content is
  1924. // associated with an old package that no longer exists, and
  1925. // delete it to keep the package registry clean.
  1926. return false;
  1927. }
  1928. // The first line in the stream is not the full path to a file or
  1929. // directory. Assume the stream content was created by a future
  1930. // version of CMake that uses a different format, and leave it.
  1931. return true;
  1932. }
  1933. void cmFindPackageCommand::FillPrefixesCMakeSystemVariable()
  1934. {
  1935. cmSearchPath& paths = this->LabeledPaths[PathLabel::CMakeSystem];
  1936. const bool install_prefix_in_list =
  1937. !this->Makefile->IsOn("CMAKE_FIND_NO_INSTALL_PREFIX");
  1938. const bool remove_install_prefix = this->NoCMakeInstallPath;
  1939. const bool add_install_prefix = !this->NoCMakeInstallPath &&
  1940. this->Makefile->IsDefinitionSet("CMAKE_FIND_USE_INSTALL_PREFIX");
  1941. // We have 3 possible states for `CMAKE_SYSTEM_PREFIX_PATH` and
  1942. // `CMAKE_INSTALL_PREFIX`.
  1943. // Either we need to remove `CMAKE_INSTALL_PREFIX`, add
  1944. // `CMAKE_INSTALL_PREFIX`, or do nothing.
  1945. //
  1946. // When we need to remove `CMAKE_INSTALL_PREFIX` we remove the Nth occurrence
  1947. // of `CMAKE_INSTALL_PREFIX` from `CMAKE_SYSTEM_PREFIX_PATH`, where `N` is
  1948. // computed by `CMakeSystemSpecificInformation.cmake` while constructing
  1949. // `CMAKE_SYSTEM_PREFIX_PATH`. This ensures that if projects / toolchains
  1950. // have removed `CMAKE_INSTALL_PREFIX` from the list, we don't remove
  1951. // some other entry by mistake
  1952. long install_prefix_count = -1;
  1953. std::string install_path_to_remove;
  1954. if (cmValue to_skip = this->Makefile->GetDefinition(
  1955. "_CMAKE_SYSTEM_PREFIX_PATH_INSTALL_PREFIX_COUNT")) {
  1956. cmStrToLong(to_skip, &install_prefix_count);
  1957. }
  1958. if (cmValue install_value = this->Makefile->GetDefinition(
  1959. "_CMAKE_SYSTEM_PREFIX_PATH_INSTALL_PREFIX_VALUE")) {
  1960. install_path_to_remove = *install_value;
  1961. }
  1962. if (remove_install_prefix && install_prefix_in_list &&
  1963. install_prefix_count > 0 && !install_path_to_remove.empty()) {
  1964. cmValue prefix_paths =
  1965. this->Makefile->GetDefinition("CMAKE_SYSTEM_PREFIX_PATH");
  1966. // remove entry from CMAKE_SYSTEM_PREFIX_PATH
  1967. std::vector<std::string> expanded = cmExpandedList(*prefix_paths);
  1968. long count = 0;
  1969. for (const auto& path : expanded) {
  1970. bool const to_add =
  1971. !(path == install_path_to_remove && ++count == install_prefix_count);
  1972. if (to_add) {
  1973. paths.AddPath(path);
  1974. }
  1975. }
  1976. } else if (add_install_prefix && !install_prefix_in_list) {
  1977. paths.AddCMakePath("CMAKE_INSTALL_PREFIX");
  1978. paths.AddCMakePath("CMAKE_SYSTEM_PREFIX_PATH");
  1979. } else {
  1980. // Otherwise the current setup of `CMAKE_SYSTEM_PREFIX_PATH` is correct
  1981. paths.AddCMakePath("CMAKE_SYSTEM_PREFIX_PATH");
  1982. }
  1983. paths.AddCMakePath("CMAKE_SYSTEM_FRAMEWORK_PATH");
  1984. paths.AddCMakePath("CMAKE_SYSTEM_APPBUNDLE_PATH");
  1985. if (this->DebugMode) {
  1986. std::string debugBuffer = "CMake variables defined in the Platform file "
  1987. "[CMAKE_FIND_USE_CMAKE_SYSTEM_PATH].\n";
  1988. collectPathsForDebug(debugBuffer, paths);
  1989. this->DebugBuffer = cmStrCat(this->DebugBuffer, debugBuffer);
  1990. }
  1991. }
  1992. void cmFindPackageCommand::FillPrefixesUserGuess()
  1993. {
  1994. cmSearchPath& paths = this->LabeledPaths[PathLabel::Guess];
  1995. for (std::string const& p : this->UserGuessArgs) {
  1996. paths.AddUserPath(p);
  1997. }
  1998. if (this->DebugMode) {
  1999. std::string debugBuffer =
  2000. "Paths specified by the find_package PATHS option.\n";
  2001. collectPathsForDebug(debugBuffer, paths);
  2002. this->DebugBuffer = cmStrCat(this->DebugBuffer, debugBuffer);
  2003. }
  2004. }
  2005. void cmFindPackageCommand::FillPrefixesUserHints()
  2006. {
  2007. cmSearchPath& paths = this->LabeledPaths[PathLabel::Hints];
  2008. for (std::string const& p : this->UserHintsArgs) {
  2009. paths.AddUserPath(p);
  2010. }
  2011. if (this->DebugMode) {
  2012. std::string debugBuffer =
  2013. "Paths specified by the find_package HINTS option.\n";
  2014. collectPathsForDebug(debugBuffer, paths);
  2015. this->DebugBuffer = cmStrCat(this->DebugBuffer, debugBuffer);
  2016. }
  2017. }
  2018. bool cmFindPackageCommand::SearchDirectory(std::string const& dir)
  2019. {
  2020. assert(!dir.empty() && dir.back() == '/');
  2021. // Check each path suffix on this directory.
  2022. for (std::string const& s : this->SearchPathSuffixes) {
  2023. std::string d = dir;
  2024. if (!s.empty()) {
  2025. d += s;
  2026. d += '/';
  2027. }
  2028. if (this->CheckDirectory(d)) {
  2029. return true;
  2030. }
  2031. }
  2032. return false;
  2033. }
  2034. bool cmFindPackageCommand::CheckDirectory(std::string const& dir)
  2035. {
  2036. assert(!dir.empty() && dir.back() == '/');
  2037. // Look for the file in this directory.
  2038. std::string const d = dir.substr(0, dir.size() - 1);
  2039. if (this->FindConfigFile(d, this->FileFound)) {
  2040. // Remove duplicate slashes.
  2041. cmSystemTools::ConvertToUnixSlashes(this->FileFound);
  2042. return true;
  2043. }
  2044. return false;
  2045. }
  2046. bool cmFindPackageCommand::FindConfigFile(std::string const& dir,
  2047. std::string& file)
  2048. {
  2049. if (this->IgnoredPaths.count(dir)) {
  2050. return false;
  2051. }
  2052. for (std::string const& c : this->Configs) {
  2053. file = cmStrCat(dir, '/', c);
  2054. if (this->DebugMode) {
  2055. this->DebugBuffer = cmStrCat(this->DebugBuffer, " ", file, "\n");
  2056. }
  2057. if (cmSystemTools::FileExists(file, true) && this->CheckVersion(file)) {
  2058. // Allow resolving symlinks when the config file is found through a link
  2059. if (this->UseRealPath) {
  2060. file = cmSystemTools::GetRealPath(file);
  2061. }
  2062. return true;
  2063. }
  2064. }
  2065. return false;
  2066. }
  2067. bool cmFindPackageCommand::CheckVersion(std::string const& config_file)
  2068. {
  2069. bool result = false; // by default, assume the version is not ok.
  2070. bool haveResult = false;
  2071. std::string version = "unknown";
  2072. // Get the filename without the .cmake extension.
  2073. std::string::size_type pos = config_file.rfind('.');
  2074. std::string version_file_base = config_file.substr(0, pos);
  2075. // Look for foo-config-version.cmake
  2076. std::string version_file = cmStrCat(version_file_base, "-version.cmake");
  2077. if (!haveResult && cmSystemTools::FileExists(version_file, true)) {
  2078. result = this->CheckVersionFile(version_file, version);
  2079. haveResult = true;
  2080. }
  2081. // Look for fooConfigVersion.cmake
  2082. version_file = cmStrCat(version_file_base, "Version.cmake");
  2083. if (!haveResult && cmSystemTools::FileExists(version_file, true)) {
  2084. result = this->CheckVersionFile(version_file, version);
  2085. haveResult = true;
  2086. }
  2087. // If no version was requested a versionless package is acceptable.
  2088. if (!haveResult && this->Version.empty()) {
  2089. result = true;
  2090. }
  2091. ConfigFileInfo configFileInfo;
  2092. configFileInfo.filename = config_file;
  2093. configFileInfo.version = version;
  2094. this->ConsideredConfigs.push_back(std::move(configFileInfo));
  2095. return result;
  2096. }
  2097. bool cmFindPackageCommand::CheckVersionFile(std::string const& version_file,
  2098. std::string& result_version)
  2099. {
  2100. // The version file will be loaded in an isolated scope.
  2101. cmMakefile::ScopePushPop const varScope(this->Makefile);
  2102. cmMakefile::PolicyPushPop const polScope(this->Makefile);
  2103. static_cast<void>(varScope);
  2104. static_cast<void>(polScope);
  2105. // Clear the output variables.
  2106. this->Makefile->RemoveDefinition("PACKAGE_VERSION");
  2107. this->Makefile->RemoveDefinition("PACKAGE_VERSION_UNSUITABLE");
  2108. this->Makefile->RemoveDefinition("PACKAGE_VERSION_COMPATIBLE");
  2109. this->Makefile->RemoveDefinition("PACKAGE_VERSION_EXACT");
  2110. // Set the input variables.
  2111. this->Makefile->AddDefinition("PACKAGE_FIND_NAME", this->Name);
  2112. this->Makefile->AddDefinition("PACKAGE_FIND_VERSION_COMPLETE",
  2113. this->VersionComplete);
  2114. auto addDefinition = [this](const std::string& variable,
  2115. cm::string_view value) {
  2116. this->Makefile->AddDefinition(variable, value);
  2117. };
  2118. this->SetVersionVariables(addDefinition, "PACKAGE_FIND_VERSION",
  2119. this->Version, this->VersionCount,
  2120. this->VersionMajor, this->VersionMinor,
  2121. this->VersionPatch, this->VersionTweak);
  2122. if (!this->VersionRange.empty()) {
  2123. this->SetVersionVariables(addDefinition, "PACKAGE_FIND_VERSION_MIN",
  2124. this->Version, this->VersionCount,
  2125. this->VersionMajor, this->VersionMinor,
  2126. this->VersionPatch, this->VersionTweak);
  2127. this->SetVersionVariables(addDefinition, "PACKAGE_FIND_VERSION_MAX",
  2128. this->VersionMax, this->VersionMaxCount,
  2129. this->VersionMaxMajor, this->VersionMaxMinor,
  2130. this->VersionMaxPatch, this->VersionMaxTweak);
  2131. this->Makefile->AddDefinition("PACKAGE_FIND_VERSION_RANGE",
  2132. this->VersionComplete);
  2133. this->Makefile->AddDefinition("PACKAGE_FIND_VERSION_RANGE_MIN",
  2134. this->VersionRangeMin);
  2135. this->Makefile->AddDefinition("PACKAGE_FIND_VERSION_RANGE_MAX",
  2136. this->VersionRangeMax);
  2137. }
  2138. // Load the version check file. Pass NoPolicyScope because we do
  2139. // our own policy push/pop independent of CMP0011.
  2140. bool suitable = false;
  2141. if (this->ReadListFile(version_file, NoPolicyScope)) {
  2142. // Check the output variables.
  2143. bool okay = this->Makefile->IsOn("PACKAGE_VERSION_EXACT");
  2144. bool const unsuitable = this->Makefile->IsOn("PACKAGE_VERSION_UNSUITABLE");
  2145. if (!okay && !this->VersionExact) {
  2146. okay = this->Makefile->IsOn("PACKAGE_VERSION_COMPATIBLE");
  2147. }
  2148. // The package is suitable if the version is okay and not
  2149. // explicitly unsuitable.
  2150. suitable = !unsuitable && (okay || this->Version.empty());
  2151. if (suitable) {
  2152. // Get the version found.
  2153. this->VersionFound =
  2154. this->Makefile->GetSafeDefinition("PACKAGE_VERSION");
  2155. // Try to parse the version number and store the results that were
  2156. // successfully parsed.
  2157. unsigned int parsed_major;
  2158. unsigned int parsed_minor;
  2159. unsigned int parsed_patch;
  2160. unsigned int parsed_tweak;
  2161. this->VersionFoundCount =
  2162. parseVersion(this->VersionFound, parsed_major, parsed_minor,
  2163. parsed_patch, parsed_tweak);
  2164. switch (this->VersionFoundCount) {
  2165. case 4:
  2166. this->VersionFoundTweak = parsed_tweak;
  2167. CM_FALLTHROUGH;
  2168. case 3:
  2169. this->VersionFoundPatch = parsed_patch;
  2170. CM_FALLTHROUGH;
  2171. case 2:
  2172. this->VersionFoundMinor = parsed_minor;
  2173. CM_FALLTHROUGH;
  2174. case 1:
  2175. this->VersionFoundMajor = parsed_major;
  2176. CM_FALLTHROUGH;
  2177. default:
  2178. break;
  2179. }
  2180. }
  2181. }
  2182. result_version = this->Makefile->GetSafeDefinition("PACKAGE_VERSION");
  2183. if (result_version.empty()) {
  2184. result_version = "unknown";
  2185. }
  2186. // Succeed if the version is suitable.
  2187. return suitable;
  2188. }
  2189. void cmFindPackageCommand::StoreVersionFound()
  2190. {
  2191. // Store the whole version string.
  2192. std::string const ver = cmStrCat(this->Name, "_VERSION");
  2193. auto addDefinition = [this](const std::string& variable,
  2194. cm::string_view value) {
  2195. this->Makefile->AddDefinition(variable, value);
  2196. };
  2197. this->SetVersionVariables(addDefinition, ver, this->VersionFound,
  2198. this->VersionFoundCount, this->VersionFoundMajor,
  2199. this->VersionFoundMinor, this->VersionFoundPatch,
  2200. this->VersionFoundTweak);
  2201. if (this->VersionFound.empty()) {
  2202. this->Makefile->RemoveDefinition(ver);
  2203. }
  2204. }
  2205. bool cmFindPackageCommand::SearchPrefix(std::string const& prefix_in)
  2206. {
  2207. assert(!prefix_in.empty() && prefix_in.back() == '/');
  2208. // Skip this if the prefix does not exist.
  2209. if (!cmSystemTools::FileIsDirectory(prefix_in)) {
  2210. return false;
  2211. }
  2212. // Skip this if it's in ignored paths.
  2213. std::string prefixWithoutSlash = prefix_in;
  2214. if (prefixWithoutSlash != "/" && prefixWithoutSlash.back() == '/') {
  2215. prefixWithoutSlash.erase(prefixWithoutSlash.length() - 1);
  2216. }
  2217. if (this->IgnoredPaths.count(prefixWithoutSlash) ||
  2218. this->IgnoredPrefixPaths.count(prefixWithoutSlash)) {
  2219. return false;
  2220. }
  2221. // PREFIX/ (useful on windows or in build trees)
  2222. if (this->SearchDirectory(prefix_in)) {
  2223. return true;
  2224. }
  2225. // Strip the trailing slash because the path generator is about to
  2226. // add one.
  2227. std::string const prefix = prefix_in.substr(0, prefix_in.size() - 1);
  2228. auto searchFn = [this](const std::string& fullPath) -> bool {
  2229. return this->SearchDirectory(fullPath);
  2230. };
  2231. auto iCMakeGen = cmCaseInsensitiveDirectoryListGenerator{ "cmake"_s };
  2232. auto firstPkgDirGen =
  2233. cmProjectDirectoryListGenerator{ this->Names, this->SortOrder,
  2234. this->SortDirection };
  2235. // PREFIX/(cmake|CMake)/ (useful on windows or in build trees)
  2236. if (TryGeneratedPaths(searchFn, prefix, iCMakeGen)) {
  2237. return true;
  2238. }
  2239. // PREFIX/(Foo|foo|FOO).*/
  2240. if (TryGeneratedPaths(searchFn, prefix, firstPkgDirGen)) {
  2241. return true;
  2242. }
  2243. // PREFIX/(Foo|foo|FOO).*/(cmake|CMake)/
  2244. if (TryGeneratedPaths(searchFn, prefix, firstPkgDirGen, iCMakeGen)) {
  2245. return true;
  2246. }
  2247. auto secondPkgDirGen =
  2248. cmProjectDirectoryListGenerator{ this->Names, this->SortOrder,
  2249. this->SortDirection };
  2250. // PREFIX/(Foo|foo|FOO).*/(cmake|CMake)/(Foo|foo|FOO).*/
  2251. if (TryGeneratedPaths(searchFn, prefix, firstPkgDirGen, iCMakeGen,
  2252. secondPkgDirGen)) {
  2253. return true;
  2254. }
  2255. // Construct list of common install locations (lib and share).
  2256. std::vector<cm::string_view> common;
  2257. std::string libArch;
  2258. if (!this->LibraryArchitecture.empty()) {
  2259. libArch = "lib/" + this->LibraryArchitecture;
  2260. common.emplace_back(libArch);
  2261. }
  2262. if (this->UseLib32Paths) {
  2263. common.emplace_back("lib32"_s);
  2264. }
  2265. if (this->UseLib64Paths) {
  2266. common.emplace_back("lib64"_s);
  2267. }
  2268. if (this->UseLibx32Paths) {
  2269. common.emplace_back("libx32"_s);
  2270. }
  2271. common.emplace_back("lib"_s);
  2272. common.emplace_back("share"_s);
  2273. auto cmnGen = cmEnumPathSegmentsGenerator{ common };
  2274. auto cmakeGen = cmAppendPathSegmentGenerator{ "cmake"_s };
  2275. // PREFIX/(lib/ARCH|lib*|share)/cmake/(Foo|foo|FOO).*/
  2276. if (TryGeneratedPaths(searchFn, prefix, cmnGen, cmakeGen, firstPkgDirGen)) {
  2277. return true;
  2278. }
  2279. // PREFIX/(lib/ARCH|lib*|share)/(Foo|foo|FOO).*/
  2280. if (TryGeneratedPaths(searchFn, prefix, cmnGen, firstPkgDirGen)) {
  2281. return true;
  2282. }
  2283. // PREFIX/(lib/ARCH|lib*|share)/(Foo|foo|FOO).*/(cmake|CMake)/
  2284. if (TryGeneratedPaths(searchFn, prefix, cmnGen, firstPkgDirGen, iCMakeGen)) {
  2285. return true;
  2286. }
  2287. // PREFIX/(Foo|foo|FOO).*/(lib/ARCH|lib*|share)/cmake/(Foo|foo|FOO).*/
  2288. if (TryGeneratedPaths(searchFn, prefix, firstPkgDirGen, cmnGen, cmakeGen,
  2289. secondPkgDirGen)) {
  2290. return true;
  2291. }
  2292. // PREFIX/(Foo|foo|FOO).*/(lib/ARCH|lib*|share)/(Foo|foo|FOO).*/
  2293. if (TryGeneratedPaths(searchFn, prefix, firstPkgDirGen, cmnGen,
  2294. secondPkgDirGen)) {
  2295. return true;
  2296. }
  2297. // PREFIX/(Foo|foo|FOO).*/(lib/ARCH|lib*|share)/(Foo|foo|FOO).*/(cmake|CMake)/
  2298. return TryGeneratedPaths(searchFn, prefix, firstPkgDirGen, cmnGen,
  2299. secondPkgDirGen, iCMakeGen);
  2300. }
  2301. bool cmFindPackageCommand::SearchFrameworkPrefix(std::string const& prefix_in)
  2302. {
  2303. assert(!prefix_in.empty() && prefix_in.back() == '/');
  2304. // Strip the trailing slash because the path generator is about to
  2305. // add one.
  2306. std::string const prefix = prefix_in.substr(0, prefix_in.size() - 1);
  2307. auto searchFn = [this](const std::string& fullPath) -> bool {
  2308. return this->SearchDirectory(fullPath);
  2309. };
  2310. auto iCMakeGen = cmCaseInsensitiveDirectoryListGenerator{ "cmake"_s };
  2311. auto fwGen =
  2312. cmMacProjectDirectoryListGenerator{ this->Names, ".framework"_s };
  2313. auto rGen = cmAppendPathSegmentGenerator{ "Resources"_s };
  2314. auto vGen = cmAppendPathSegmentGenerator{ "Versions"_s };
  2315. auto grGen = cmFileListGeneratorGlob{ "/*/Resources"_s };
  2316. // <prefix>/Foo.framework/Resources/
  2317. if (TryGeneratedPaths(searchFn, prefix, fwGen, rGen)) {
  2318. return true;
  2319. }
  2320. // <prefix>/Foo.framework/Resources/CMake/
  2321. if (TryGeneratedPaths(searchFn, prefix, fwGen, rGen, iCMakeGen)) {
  2322. return true;
  2323. }
  2324. // <prefix>/Foo.framework/Versions/*/Resources/
  2325. if (TryGeneratedPaths(searchFn, prefix, fwGen, vGen, grGen)) {
  2326. return true;
  2327. }
  2328. // <prefix>/Foo.framework/Versions/*/Resources/CMake/
  2329. return TryGeneratedPaths(searchFn, prefix, fwGen, vGen, grGen, iCMakeGen);
  2330. }
  2331. bool cmFindPackageCommand::SearchAppBundlePrefix(std::string const& prefix_in)
  2332. {
  2333. assert(!prefix_in.empty() && prefix_in.back() == '/');
  2334. // Strip the trailing slash because the path generator is about to
  2335. // add one.
  2336. std::string const prefix = prefix_in.substr(0, prefix_in.size() - 1);
  2337. auto searchFn = [this](const std::string& fullPath) -> bool {
  2338. return this->SearchDirectory(fullPath);
  2339. };
  2340. auto appGen = cmMacProjectDirectoryListGenerator{ this->Names, ".app"_s };
  2341. auto crGen = cmAppendPathSegmentGenerator{ "Contents/Resources"_s };
  2342. // <prefix>/Foo.app/Contents/Resources
  2343. if (TryGeneratedPaths(searchFn, prefix, appGen, crGen)) {
  2344. return true;
  2345. }
  2346. // <prefix>/Foo.app/Contents/Resources/CMake
  2347. return TryGeneratedPaths(
  2348. searchFn, prefix, appGen, crGen,
  2349. cmCaseInsensitiveDirectoryListGenerator{ "cmake"_s });
  2350. }
  2351. // TODO: Debug cmsys::Glob double slash problem.
  2352. bool cmFindPackage(std::vector<std::string> const& args,
  2353. cmExecutionStatus& status)
  2354. {
  2355. return cmFindPackageCommand(status).InitialPass(args);
  2356. }