cmFindPackageCommand.cxx 70 KB

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