cmFindPackageCommand.cxx 94 KB

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