cmFindPackageCommand.cxx 131 KB

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