cmFindPackageCommand.cxx 94 KB

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