cmFindPackageCommand.cxx 68 KB

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