cmFindPackageCommand.cxx 129 KB

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