cmFindPackageCommand.cxx 114 KB

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