cmFindPackageCommand.cxx 71 KB

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