cmFindPackageCommand.cxx 102 KB

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