cmFindPackageCommand.cxx 69 KB

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