cmFindPackageCommand.cxx 126 KB

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