cmFindPackageCommand.cxx 115 KB

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