cmFindPackageCommand.cxx 93 KB

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