1
0

cmFindPackageCommand.cxx 94 KB

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