cmFindPackageCommand.cxx 93 KB

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