cmFindPackageCommand.cxx 127 KB

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