cmFindPackageCommand.cxx 91 KB

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