cmFindPackageCommand.cxx 93 KB

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