cmFindPackageCommand.cxx 94 KB

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