cmFindPackageCommand.cxx 98 KB

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