cmFindPackageCommand.cxx 93 KB

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