cmFindPackageCommand.cxx 114 KB

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