cmFindPackageCommand.cxx 89 KB

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