cmFindPackageCommand.cxx 100 KB

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