cmFindPackageCommand.cxx 90 KB

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