cmFindPackageCommand.cxx 108 KB

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