cmFindPackageCommand.cxx 125 KB

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