cmFindPackageCommand.cxx 93 KB

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