cmFindPackageCommand.cxx 71 KB

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