cmFindPackageCommand.cxx 93 KB

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