cmFindPackageCommand.cxx 71 KB

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