cmFindPackageCommand.cxx 129 KB

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