cmFindPackageCommand.cxx 93 KB

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