cmFindPackageCommand.cxx 91 KB

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